In a recent interview, I was asked to answer if this code is safe and if it is when would I use something like this:
template<class T> T *CTricky<T>::Safe_Or_Not (T *object)
{
object->T::~T ();
::new (object) T;
return object;
}
My answer was: this code is safe and I would use this technique if I needed to free the resources used by my "object" by calling its destructor, but at the same time I didn't want to deallocate my "object" and wanted it to hold its place in memory (achieved by placement new here).
I honestly am not looking for help to answer this question correctly on the interview. I'm only curious to see if my understanding of placement new and explicit destructor calls are correct.
It is NOT safe: Following may produce memory leak: (https://ideone.com/70YqhM)
Base* b = new Derived;
b = Safe_Or_Not(b);
Derived destructor is never called.
And as other mention: