Advertisement
Guest User

Untitled

a guest
Apr 11th, 2012
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <ext/mt_allocator.h>
  2. #include <cstdio>
  3. #include <new>
  4. #include <vector>
  5.  
  6. template < typename T, typename A = std::allocator< T > >
  7. struct overload_new_delete
  8. {
  9.         static A allocator;
  10.  
  11.         static void* operator new ( std::size_t size )
  12.         {
  13.                 return allocator.allocate ( size );
  14.         }
  15.         static void* operator new ( std::size_t size, void* place )
  16.         {
  17.                 return ::operator new ( size, place );
  18.         }
  19.         static void operator delete ( void* p, std::size_t size )
  20.         {
  21.                 allocator.deallocate ( reinterpret_cast< T* >( p ), size );
  22.         }
  23.         static void operator delete ( void* p, void * place )
  24.         {
  25.                 ::operator delete ( p, place );
  26.         }
  27.         static void* operator new [] ( std::size_t size )
  28.         {
  29.                 return allocator.allocate ( size );
  30.         }
  31.         static void* operator new [] ( std::size_t size, void* place )
  32.         {
  33.                 return ::operator new ( size, place );
  34.         }
  35.         static void operator delete [] ( void* p, std::size_t size )
  36.         {
  37.                 allocator.deallocate ( reinterpret_cast< T* >( p ), size );
  38.         }
  39.         static void operator delete [] ( void* p, void* place )
  40.         {
  41.                 ::operator delete ( p, place );
  42.         }
  43. };
  44.  
  45. template < typename T, typename A >
  46. A overload_new_delete< T, A >::allocator;
  47.  
  48. struct X : overload_new_delete< X, __gnu_cxx::__mt_alloc< X > >
  49. {
  50.     X( int i ) : i_( i ) { }
  51.     int i_;
  52. };
  53.  
  54. int main()
  55. {
  56.     X* x1 = new X( 7 );
  57.     std::printf( "x1 = %p, *x1 = %d\n", x1, x1->i_ );
  58.     X* x2 = new X( 42 );
  59.     std::printf( "x2 = %p, *x2 = %d\n", x2, x2->i_ );
  60.     delete x1;
  61.     delete x2;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement