标签:
1 template<class T> 2 classvector 3 { 4 public: 5 vector():elements(0),first_free(0),end(0){} 6 void push_back(const T&); 7 //… 8 private: 9 static std::allocator<T> alloc; 10 void reallocate(); 11 T* elements; 12 T* first_free; 13 T* end; 14 //… 15 };
1 tmplate <class T> 2 voidvector<T>::push_back(const T& t) 3 { 4 //are we out of space 5 if(first_free == end) 6 reallocate();// gets more space and copies existing elements to it 7 alloc.construct(first_free,t); 8 ++first_free; 9 } 10 tmplate <class T> 11 voidvector<T>::reallocate() 12 { 13 std::ptrdiff_t size = first_free – elements; 14 std::ptrdiff_t newcapacity =2* max(size,1); 15 16 T* newelements = alloc.allocate(newcapacity); 17 18 uninitialized_copy(elements,first_free,newelements); 19 20 for(T *p = first_free; p != elements;} 21 alloc.destroy(--p); 22 23 if(elements) 24 alloc.deallocate(elements,end-elements); 25 elements = newelements; 26 first_free = elements + size; 27 end = elements + newcapacity; 28 }
1 //new expression 2 string *sp =new string(“initialized”);
首先,该表达式调用名为 operator new 的标准库函数,分配足够大的原始的未类型化的内存;
1 delete sp;
首先,对 sp 指向的对象运行适当的析构函数;
1 void*operator new(size_t); 2 void*operator new[](size_t); 3 void*operator new(std::size_t size,void* ptr)throw();//placement 4 5 void*operator delete(void*); 6 void*operator delete[](void*);
1 std::allocator<std::string> alloc; 2 string *sp = alloc.allocate(2);// allocate space to hold 2 strings 3 new(sp) string(b,e); 4 alloc.construct(sp +1, string(b,e));
1 template<class T> 2 classCachedObj 3 { 4 public: 5 void*operatornew(std::size_t); 6 void*operatordelete(void*, std::size_t); 7 virtual~CachedObj(){} 8 protected: 9 T* next; 10 private: 11 staticvoid add_to_freelist(T*); 12 static std::allocator<T> alloc_mem; 13 static T* freeStore; 14 staticconst std::size_t chunk; 15 }
1 template<class T> 2 void*CachedObj<T>::operatornew(size_t sz) 3 { 4 if(sz !=sizeof(T)) returnnullptr; 5 if(!freeStore) 6 { 7 T* array = alloc_mem.allocate(chunk); 8 for(size_t i =0; I != chunk;++i) 9 add_to_freelist(&array[i]); 10 } 11 T*p = freeStore; 12 freeStore = freeSore->CachedObj<T>::next; 13 return p; 14 } 15 template<class T> 16 voidCachedObj<T>::add_to_freelist(T*p) 17 { 18 p->CachedObj<T>::next = freeStore; 19 freeStore = p; 20 } 21 template<class T> 22 voidCachedObj<T>::operatordelete(void*p) 23 { 24 if(p !=0) 25 add_to_freelist(static_cast<T*>(p)); 26 }
1 template<classType> 2 classQueueItem: 3 publicCachedObj<QueueItem<Type>>{};
标签:
原文地址:http://www.cnblogs.com/codetravel/p/4705253.html