Вы должны сделать немного больше, чем то, что вы делаете в своем коде.Это минимальный код, необходимый для того, чтобы заставить его работать так, как вы хотите:
template<typename T>
class MyAlloc : public std::allocator <T>
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template<typename U>
struct rebind
{
typedef MyAlloc <U> other;
};
MyAlloc() {}
template<typename U>
MyAlloc(const MyAlloc<U>&) {}
void construct(pointer p, const_reference t){
std::cout << "Construct in the allocator" << std::endl;
new( (void*)p ) MyObj(t);
}
};
И затем использовать его как:
int main(){
MyObj x;
std::list <MyObj,MyAlloc<MyObj> > list(5,x);
}
Вывод (по вашему желанию)):
This is the constructor
Construct in the allocator
This is the copy constructor
Construct in the allocator
This is the copy constructor
Construct in the allocator
This is the copy constructor
Construct in the allocator
This is the copy constructor
Construct in the allocator
This is the copy constructor
Демонстрация в сети: http://www.ideone.com/QKdqm
Вся идея этого минимального кода заключается в переопределении определения rebind
шаблона класса в базовом классе std::allocator
, которыйопределяется как:
template<typename U>
struct rebind
{
typedef std::allocator<U> other;
};
, когда на самом деле нам это нужно:
template<typename U>
struct rebind
{
typedef MyAlloc<U> other;
};
Поскольку в конечном итоге это rebind<U>::other
, который используется в качестве распределителя.
Кстати, typedefs необходимы, чтобы привести имена (типов) в область видимости производного класса (по умолчанию они не видны, так как MyAlloc
теперь является шаблоном класса).Таким образом, вы можете написать это как:
template<typename T>
class MyAlloc : public std::allocator <T>
{
typedef std::allocator <T> base;
public:
typedef typename base::size_type size_type;
typedef typename base::difference_type difference_type;
typedef typename base::pointer pointer;
typedef typename base::const_pointer const_pointer;
typedef typename base::reference reference;
typedef typename base::const_reference const_reference;
typedef typename base::value_type value_type;
//same as before
};
Результат будет таким же: http://www.ideone.com/LvQhI