get_allocator函数
语法:
1 |
allocator_type get_allocator() const; |
get_allocator() 返回vector的内存分配器
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
allocator_type get_allocator() const { return *static_cast<const _Alloc*>(&this->_M_impl); } /** * @brief The "standard" allocator, as per [20.4]. * * (See @link Allocators allocators info @endlink for more.) */ template<typename _Tp> class allocator: public ___glibcxx_base_allocator<_Tp> { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp* pointer; typedef const _Tp* const_pointer; typedef _Tp& reference; typedef const _Tp& const_reference; typedef _Tp value_type; template<typename _Tp1> struct rebind { typedef allocator<_Tp1> other; }; allocator() throw() { } allocator(const allocator& a) throw() : ___glibcxx_base_allocator<_Tp>(a) { } template<typename _Tp1> allocator(const allocator<_Tp1>&) throw() { } ~allocator() throw() { } // Inherit everything else. }; |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1; int * p; unsigned int i; p = v1.get_allocator().allocate(5); for (i=0; i<5; i++) v1.get_allocator().construct(&p[i],i); for (i=0; i<5; i++){ cout << ' ' << p[i]; } cout << '\n'; for (i=0; i<5; i++) v1.get_allocator().destroy(&p[i]); v1.get_allocator().deallocate(p,5); } |
测试结果:
1 |
0 1 2 3 4 |