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:Placement
newis really just an overload of theoperator newfunction 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 theconstructmethod which is used (among others) by the STL container classes to construct objects.Since placement
newonly constructs an object without allocating memory, it’s usually an error to calldeleteto get rid of the memory. Destruction has to happen by calling the destructor directly, without freeing the memory: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().