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++ 中的就地构造函数?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
