Placement New Operator ใน C++
Placement new เป็นรูปแบบหนึ่งของ operator new ปกติ new ทำ 2 อย่าง: จองหน่วยความจำ และสร้างออบเจ็กต์ในหน่วยความจำนั้น new ธรรมดาจองใน heap แต placement new สร้างออบเจ็กต์ที่ address ที่กำหนด ไม่มี placement delete ต้องจัดการหน่วยความจำเอง
Placement new ใช้ "สร้าง" ออบเจ็กต์บนหน่วยความจำที่จองไว้แล้ว เหมาะสำหรับ optimization เร็วกว่าการจองใหม่ ใช้รูปแบบ:
new (address) (type) initializer
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int main() {
int a = 5;
cout << "a = " << a << endl;
cout << "&a = " << &a << endl;
// Placement new เปลี่ยนค่า a เป็น 10
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