“placement new” 的 C++ 用途是什么?


简而言之,“placement new” 允许你在已分配给给定变量的内存上“构造”一个对象。这对于优化很有用,因为它不需要重新分配和重复使用已分配给它的内存,从而可以加快速度。它可以用作如下形式 −

new (address) (type) initializer

我们可以指定要构建给定类型的对象的新地址。 

示例

#include<iostream>
using namespace std;
int main() {
   int a = 5;
   cout << "a = " << a << endl;
   cout << "&a = " << &a << endl;

   // Placement new changes the value of X to 100
   int *m = new (&a) int(10);

   cout << "\nAfter using placement new:" << endl;
   cout << "a = " << a << endl;
   cout << "m = " << m << endl;
   cout << "&a = " << &a << endl;

   return 0;
}

输出

这将输出 −

a = 5
&a = 0x60ff18

使用 placement new 之后 −

a = 10
m = 0x60ff18
&a = 0x60ff18

更新于: 2020 年 6 月 24 日

284 次浏览

开始你的职业

完成课程后获得认证

开始
广告
© . All rights reserved.