Advertisement
PiMaster

STL implementation

Jul 14th, 2011
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. template<class T>
  2. T* allocate(size_t n){
  3.     //allocate an array of chars large enough to hold n instances of T
  4.     return (T*)(new char[n*sizeof(T)]);}
  5.  
  6. template<class T>
  7. void deallocate(T* p){
  8.     //delete it as a char array to avoid calling destructors
  9.     delete[] (char*)p;}
  10.  
  11. template<class T>
  12. void construct(T* p,const T& t=T()){
  13.     new ((void*)p) T(t);}
  14.  
  15. template<class T>
  16. void deconstruct(T* p){
  17.     p->~T();}
  18.  
  19. class testclass{
  20.     public:
  21.         ~testclass(){
  22.             printf("Deconstructor called");}};
  23.  
  24. //example use
  25. int main(){
  26.     testclass* array=allocate<testclass>(10);
  27.     //increase the virtual array size to 1
  28.     construct<testclass>(array);
  29.     //... do as many construct's as you want
  30.     deconstruct<testclass>(array);
  31.     //... call deconstruct for every construct
  32.     deallocate<testclass>(array);}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement