C++ Placement new
示例
在某些情况下,我们不想依靠FreeStore分配内存,而我们想使用的自定义内存分配new。
在这种情况下,我们可以使用PlacementNew,在这里我们可以告诉'new'运算符从预先分配的内存位置分配内存
例如
int a4byteInteger; char *a4byteChar = new (&a4byteInteger) char[4];
在此示例中,所指向的内存a4byteChar是通过整数变量分配给“堆栈”的4个字节a4byteInteger。
这种内存分配的好处是程序员可以控制分配。在上面的示例中,由于a4byteInteger是在堆栈上分配的,因此我们无需显式调用“删除a4byteChar”。
对于动态分配的内存,也可以实现相同的行为。例如
int *a8byteDynamicInteger = new int[2]; char *a8byteChar = new (a8byteDynamicInteger) char[8];
在这种情况下,内存指针bya8byteChar将引用由分配的动态内存a8byteDynamicInteger。但是,在这种情况下,我们需要显式调用deletea8byteDynamicInteger以释放内存
C++类的另一个示例
struct ComplexType {
int a;
ComplexType() : a(0) {}
~ComplexType() {}
};
int main() {
char* dynArray = new char[256];
//调用ComplexType的构造函数以将内存初始化为ComplexType
new((void*)dynArray) ComplexType();
//完成后清理内存
reinterpret_cast<ComplexType*>(dynArray)->~ComplexType();
delete[] dynArray;
//堆栈存储器也可以与新的放置一起使用
alignas(ComplexType) char localArray[256]; //alignas()自C++11起可用
new((void*)localArray) ComplexType();
//只需要调用析构函数来获取堆栈内存
reinterpret_cast<ComplexType*>(localArray)->~ComplexType();
return 0;
}