“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.