I have a fictional class:
template<typename T> class demonstration
{
public:
demonstration(){}
...
T *m_data;
}
At some point in the program's execution, I want to set m_data to a big block of allocated memory and construct an object T there.
At the moment, I've been using this code:
void construct()
{
*m_data = T();
}
Which I've now realised is probably not the best idea... wont work under certain cirumstances, if T has a private assignment operator for example.
Is there a normal/better way to do what I'm attempting here?
Use placement new:
new (m_data) T();
Placement new is really just an overload of the operator new function that accepts an additional parameter – the memory location where the object should be constructed at. This precisely matches your use-case.
In particular, this is how allocators usually implement the construct method which is used (among others) by the STL container classes to construct objects.
Since placement new only constructs an object without allocating memory, it’s usually an error to call delete to get rid of the memory. Destruction has to happen by calling the destructor directly, without freeing the memory:
m_data->~T();
Notice that this syntax for calling the destructor doesn’t work for a constructor call, otherwise we wouldn’t need placement new in the first place. I.e. there’s no m_data->T().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With