Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Placement new ใน C++ ใช้ทำอะไร


Placement new ให้สร้าง (construct) object บนหน่วยความจำที่ จัดสรรไว้แล้ว (pre-allocated) แทนที่จะ allocate ใหม่

รูปแบบ: new (address) Type(initializer)

ประโยชน์: optimization - เร็วกว่า (ไม่ต้อง allocate ใหม่) reuse memory เหมาะสำหรับ memory pools, custom allocators, embedded systems

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    int a = 5;
    cout << "a = " << a << endl;
    cout << "&a = " << &a << endl;
    // Placement new: construct int(10) ที่ address ของ a
    int *m = new (&a) int(10);
    cout << "\nAfter placement new:" << endl;
    cout << "a = " << a << endl;   // 10
    cout << "m = " << m << endl;   // address เดียวกับ &a
    cout << "&a = " << &a << endl;
    return 0;
}

ผลลัพธ์

a = 5
&a = 0x60ff18

After placement new:
a = 10
m = 0x60ff18
&a = 0x60ff18

ข้อควรระวัง: ต้องเรียก destructor ด้วยตนเองสำหรับ object ที่สร้างด้วย placement new (ไม่มี auto cleanup)