简体   繁体   中英

Calling constructor of a template class

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM