问题描述
c ++中的new运算符有很多面孔,但是我对new放置感兴趣.
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
在这种情况下如何正确分配内存?如果我不使用内置类型int而是使用名为myClass的类怎么办?
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
感谢您的帮助.
推荐答案
在第一种情况下,由于int
没有构造函数,因此没有必要使用new放置.
In the first case, there's no point in using placement new, since int
doesn't have a constructor.
在第二种情况下,它是没有意义的(如果myClass
是微不足道的)或错误的,因为数组中已经有对象.
In the second case, it's either pointless (if myClass
is trivial) or wrong, since there are already objects in the array.
您可以使用new放置来初始化内存块中的对象,该对象必须适当对齐,并且不能已经包含(非平凡的)对象.
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.
这篇关于如何删除分配了新展示位置的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!