views:

145

answers:

2

I have a pool manager template class. When a class object gets added back to the pool manager I would like to reset it back to it's initial state. I would like to call the placment destructor and placment constructor on it so it gets fully reset for the next time it is given out by the pool manager. I've tried many ways to get this to work but I'm stumped. Here is an example of what I have tried.

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
}

I've tried a bunch of different syntaxes and none seem to work. The code itself is cross platform so should compile using gcc ( under mingw or linux or mac ) and for windows I'm still using vs 2003.

+3  A: 

How about:

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...
}
e.James
I tried this 'obj = new (location)T();' and get a compile error, something about location, maybe VS 2003 is buggy and I new a new version of VS??
KPexEA
Calling delete will release its memory, if you are lucky you will get an access violation.
Ismael
yeah what u want is just do obj->~T(); instead of teh delete
Johannes Schaub - litb
@xhantt: Where would the access violation come from? We never use obj in an unreleased state.
e.James
Also `new ((void*)obj) T();` compile fine win VS 2005.
Ismael
@litb: Hmmm. That's what the OP had in his code. I'll make the change.
e.James
The placement new doesn't allocate new memory it only uses the memory you have passed as parameter.
Ismael
@xhantt: Ah. That makes sense. I've changed the code. Thank you for the lesson :)
e.James
+2  A: 

Boost has a Pool library. It might be easier to just use theirs instead of writing your own.

Michael Kohne