什么是 C++ 中的就地构造函数?
可能的重复:
C++的“placement new”
什么是 C++ 中的就地构造函数?
What is an in-place constructor in C++?
例如Datatype *x = new(y) Datatype();
推荐答案
这称为放置新操作符.它允许您提供将分配数据的内存,而无需 new
运算符分配它.例如:
This is called the placement new operator. It allows you to supply the memory the data will be allocated in without having the new
operator allocate it. For example:
Foo * f = new Foo();
上面会为你分配内存.
void * fm = malloc(sizeof(Foo));
Foo *f = new (fm) Foo();
以上将使用调用malloc
分配的内存.new
不会再分配了.但是,您不仅限于课程.您可以对通过调用 new
分配的任何类型使用放置 new 运算符.
The above will use the memory allocated by the call to malloc
. new
will not allocate any more. You are not, however, limited to classes. You can use a placement new operator for any type you would allocate with a call to new
.
placement new 的一个问题"是,您不应该释放通过使用delete
关键字调用placement new 运算符所分配的内存.您将通过直接调用析构函数来销毁对象.
A 'gotcha' for placement new is that you should not release the memory allocated by a call to the placement new operator using the delete
keyword. You will destroy the object by calling the destructor directly.
f->~Foo();
手动调用析构函数后,内存可以按预期释放.
After the destructor is manually called, the memory can then be freed as expected.
free(fm);
相关文章