0

I have a container class which has a pre allocated buffer. I am calling memset() to use pre-allocated memory to create my objects. Since I am not using new, the constructor is not called.

Here is a simplified version of the add function

 template<typename T>
 T* CContainer<T>::Add()
 {
memset(&m_pBuffer[index],0,index);
T* pReturnValue = reinterpret_cast<T*> ( &m_pBuffer[index] );

return pReturnValue;
 }

Any way to call the constructor of template class T.

Thanks for your help.

Marc Baumbach
  • 10,323
  • 2
  • 30
  • 45
Codesmith
  • 85
  • 1
  • 11
  • 1
    Use "placement new". [This](http://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new) has a good explanation. – cole Feb 02 '13 at 08:52

1 Answers1

3

To call the constructor of an object in an existing piece of memory use placement new.

In your case add this line right before the return statement:

new (pReturnValue) T;

To destroy the instance, call the destructor explicitly:

pReturnValue->~T();
Stefan Dragnev
  • 14,143
  • 6
  • 48
  • 52