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++ 中的就地构造函数?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01