C++ 中“placement new”有什么用?
简而言之,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
广告