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
廣告