Allocator
Posted masteryan576356467
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Allocator相关的知识,希望对你有一定的参考价值。
// 内存分配器 Allocator #include <vector> #include <iostream> using namespace std; template<typename _Ty> struct Allocator_base { using value_type = _Ty; }; template<typename _Ty> struct Allocator_base<const _Ty> { using value_type = _Ty; }; template<typename _Ty> class Allocator : public Allocator_base<_Ty> { public: //inner type of data typedef size_t size_type; typedef ptrdiff_t difference_type; //type of the minus of two pointers typedef _Ty* pointer; typedef _Ty& reference; typedef const _Ty& const_reference; typedef const _Ty* const_pointer; typedef Allocator_base<_Ty> _My_base; typedef typename _My_base::value_type value_type; template<typename _U> struct rebind { typedef Allocator<_U> other; // type_cast if the type is difference(type not unique) }; Allocator() = default; Allocator(const Allocator&) = default; template<typename _otherAll> Allocator(const Allocator<_otherAll>&) noexcept {}; ~Allocator() = default; //apply memory pointer allocate(size_type num, typename Allocator<_Ty>::const_reference hint = 0) { //------------------------------show information static int i = 0; ++i; cout << endl; cout << "the nums of allocate memory :" << num << endl;; cout << "------------------------------------------ "; cout << "allcation of room " << num << endl; //----------------------------- return (pointer)(::operator new(num * sizeof(_Ty))); } // construct obj in memory void construct(pointer p, const_reference value) { new (p)_Ty(value); // (one of overloads of operator new) placement new } //destory obj void destory(pointer p) { p->~Ty(); } // relese memory void deallocate(pointer p, size_type size) { ::operator delete(p); } }; // test code template<typename T> void print(vector<T, Allocator<T>>& v) { cout << "the capacity of container is " << v.capacity() << " "; cout << "the size of container is " << v.size() << endl; for(auto i : v) cout << i << ‘ ‘; cout << endl; } int main() { vector<int, Allocator<int>> vec{1,2,3}; print(vec); for(int i = 0; i < 10; ++i) { vec.push_back(10 * i); print(vec); } return 0; }
以上是关于Allocator的主要内容,如果未能解决你的问题,请参考以下文章
对“std::vector<int, std::allocator<int>>”类型空指针的引用绑定
C++ allocator::allocate 是不是应该抛出?
Xcode5.1.1 and Xcode6 beta7 iOS7.1 64-bit [Allocator] Allocator invalid, fall back to malloc