如何使用placment从模板中删除/新建一个类?
问题描述:
我有一个池管理器模板类。当一个类对象被添加回池管理器时,我想重置它回到它的初始状态。我想调用它的placment destructor和placment构造函数,以便在下次由池管理器发出时进行完全重置。我已经尝试了很多方法来使这个工作,但我很难过。这是我尝试过的一个例子。如何使用placment从模板中删除/新建一个类?
template <class T>
void PoolClass<T>::ReleaseToPool(T *obj)
{
obj->~T(); //call destructor
obj->T::T(); //call constructor
//also tried new (obj)T(); //but this doesn't seem to work either
//then misc code to add a pointer to the object
//to my list of available objects for re-use later
}
我试过一堆不同的语法,似乎没有工作。代码本身是跨平台,应该编译使用gcc(下MinGW的或Linux或Mac)和Windows我仍然使用VS 2003
答
如何:
template <class T>
void PoolClass<T>::ReleaseToPool(T *obj)
{
obj->~T(); //call destructor
obj = new ((void *)obj)T(); //call constructor
// add a pointer to the object to the list...
}
你有没有试过这个http://stackoverflow.com/questions/362953/what-are-uses-of-the-c-construct-placement-new?即铸造obj为void * – Ismael 2009-01-28 19:18:59
是的,我试着将它铸造成无效,然后做新(voidobj)T();在这个时候我怀疑VS2003是越野车,我需要升级。 – KPexEA 2009-01-28 19:51:12