how do you delete an object allocated with placement new

感情迁移 提交于 2019-12-07 07:09:51

问题


there are quite a few faces for the new operator in c++, but I'm interested in placement new.

Suppose you allocate memory at a specific memory location

 int memoryPool[poolSize*sizeof(int)];
 int* p = new (mem) int; //allocates memory inside the memoryPool buffer

 delete p; //segmentation fault 

How can I correctly deallocate memory in this case? What if instead of built-in type int I would use some class called myClass?

 myClass memoryPool[poolSize*sizeof(myClass )];
 myClass * p = new (mem) myClass ; //allocates memory inside the memoryPool buffer

 delete p; //segmentation fault 

Thanks for your help.


回答1:


In the first case, there's no point in using placement new, since int doesn't have a constructor.

In the second case, it's either pointless (if myClass is trivial) or wrong, since there are already objects in the array.

You use placement new to initialise an object in a block of memory, which must be suitably aligned, and mustn't already contain a (non-trivial) object.

char memory[enough_bytes];  // WARNING: may not be properly aligned.
myClass * c = new (memory) myClass;

Once you've finished with it, you need to destroy the object by calling its destructor:

c->~myClass();

This separates the object's lifetime from that of its memory. You might also have to release the memory at some point, depending on how you allocated it; in this case, it's an automatic array, so it's automatically released when it goes out of scope.




回答2:


In your case there is no need to deallocate it, your int array will be deallocated once you return from your function. You should only call explicitly your destructor:

p->~myclass();


to keep you buffer correctly aligned use std::aligned_storage, look in here for example:

http://www.cplusplus.com/reference/type_traits/aligned_storage/



来源:https://stackoverflow.com/questions/21551972/how-do-you-delete-an-object-allocated-with-placement-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!