What is an in-place constructor in C++?(什么是 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);
这篇关于什么是 C++ 中的就地构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是 C++ 中的就地构造函数?


- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01