C++ 中“placement new”有哪些用途?
在本節中,我們將瞭解 C++ 中的 placement new 運算子。placement new 是 new 運算子的另一種變體。常規 new 運算子執行兩件事。它分配記憶體,然後在分配的記憶體中構造一個物件。
new 運算子在堆部分中分配記憶體並在其中構造物件。但是對於 placement new 運算子,它會在給定的地址處構造物件。要釋放記憶體,如果使用 new 運算子分配記憶體,我們可以使用 delete 關鍵字。但是對於 placement new,沒有 placement delete 特性。
因此,簡而言之,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 = 0x22fe34 After using placement new: a = 10 m = 0x22fe34 &a = 0x22fe34
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP