How do you delete an object selected using the new placement

for a new operator in C ++, there are quite a few people, but I'm interested in placing new.

Suppose you allocated memory in 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 free memory correctly in this case? What if, instead of the int 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 

Thank you for your help.

+4
source share
2 answers

In the first case, it makes no sense to use a new placement, since it intdoes not have a constructor.

( myClass ), , .

, () .

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

, , :

c->~myClass();

. , - , , ; , , .

+4

, int . :

p > ~ MyClass();


, std:: aligned_storage, , :

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

+1

Source: https://habr.com/ru/post/1525211/


All Articles