Forcing a templated object to be created from a pointer

I have a fictional class:

template<typename T> class demonstration
{  
    public:
    demonstration(){}
    ...
    T *m_data;
}

      

At some point in the execution of the program, I want to install m_data

in a large block of allocated memory and build an object there T

.

I am currently using this code:

void construct()
{
    *m_data = T();
}

      

What I just figured out might not be the best idea ... doesn't work under certain conditions if it T

has a private assignment operator, for example.

Is there a normal / better way to do what I'm trying here?

+2


a source to share


2 answers


Use placement new

:

new (m_data) T();

      

Allocation new

is really just a function overload operator new

that takes an extra parameter - the memory location where the object should be constructed. This fits your use case exactly.

In particular, this is how the allocator

method construct

that is used (in particular) by the container STL classes to create objects usually implements .



Since allocation new

only creates an object without allocating memory, it is usually an error to call delete

to get rid of memory. Destruction should happen by calling the destructor directly without freeing memory:

m_data->~T();

      

Note that this syntax for calling a destructor does not work for calling a constructor, otherwise we would not need the placement in the first place. That is, theres no m_data->T()

.

+8


a source


The placement operator new

is what suits your situation.



+1


a source







All Articles