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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <memory>
template <typename T>
class MyAllocator : public std::allocator<T> {
typedef typename std::allocator<T> BaseType;
typedef typename BaseType::size_type size_type;
typedef typename BaseType::pointer pointer;
public:
MyAllocator()
{ printf( "MyAllocator Constructor.\n" );}
MyAllocator( const MyAllocator &rhs )
{printf( "MyAllocator Copy Constructor.\n" );}
~MyAllocator()
{ printf( "MyAllocator Destructor.\n" );}
pointer allocate( size_type _Count, const void* _Hint )
{
printf( "MyAllocator::allocate() count = %u, hint = %x\n", _Count, _Hint );
return BaseType::allocate( _Count, _Hint );
}
void deallocate( pointer _Ptr, size_type _Count )
{
printf( "MyAllocator::deallocate() ptr = %x, count = %u\n", _Ptr, _Count );
BaseType::deallocate( _Ptr, _Count );
}
void construct( pointer _Ptr, const T &_Val )
{
printf( "MyAllocator::construct() ptr = %x\n", _Ptr );
BaseType::construct( _Ptr, _Val );
}
void destroy( pointer _Ptr )
{
printf( "MyAllocator::destroy() ptr = %x\n", _Ptr );
BaseType::destroy( _Ptr );
}
};
struct Test {
Test()
{ printf( "Test Constructor.\n" ); }
Test( const Test &rhs )
{ printf( "Test Copy Constructor.\n" ); }
~Test()
{ printf( "Test Destructor.\n" ); }
int x;
};
class MyString : public std::basic_string< char, std::char_traits<char>, MyAllocator<char> > {
};
template <typename T>
class MyVector : public std::vector< T, MyAllocator<T> > {
};
int main()
{
// MyVector test
{
MyVector<int> vec;
printf( "test\n" );
vec.reserve(100);
vec.push_back(1);
vec.push_back(2);
printf( "%u, %u\n", vec.size(), vec.capacity() );
}
// MyString test
{
MyString s;
s.append("Hello, world!" );
}
return 0;
}
|