我制作了一个模板,该模板可以采用自定义分配器,如下所示:
template<typename Key,typename Alloc=std::allocator<Key>>
struct node {
typedef typename Alloc::template rebind<node>::other allocator_type;
void* operator new(size_t size) {
node* n = _node_allocator.allocate(1);
_node_allocator.construct(n, _node_init_val);
return n;
}
void operator delete(void * n)
{
_node_allocator.destroy(static_cast<node*>(n));
_node_allocator.deallocate(static_cast<node*>(n), 1);
}
node() {std::cout<<"Constr init"<<std::endl;}
node(Key x):_k(x) {std::cout<<"Constructor"<<std::endl;}
~node() { std::cout<<"Destructor"<<std::endl;}
protected:
Key _k;
static allocator_type _node_allocator;
static const node _node_init_val;
};
template<typename Key,typename Alloc>
const node<Key,Alloc> node<Key,Alloc>::_node_init_val;
template<typename Key,typename Alloc>
typename node<Key,Alloc>::allocator_type node<Key,Alloc>::_node_allocator;
int main() {
node<int>* p=new node<int>(5);
delete p;
std::cout<<"END"<<std::endl;
return 0;
}
不幸的是,析构函数被调用了两次,因为delete总是隐式调用析构函数,但是我认为这样做不会,因为分配是由 _node_allocator并因此也应使用_node_allocator进行销毁。我该怎么做?