การจำกัดการจองหน่วยความจำแบบไดนามิกของออบเจ็กต์ (Restrict Dynamic Allocation of Objects) ใน C++
ทำให้คลาสไม่สามารถสร้างออบเจ็กต์ด้วย new (dynamic allocation) ได้ โดยตั้งค่า operator new เป็น private
ตัวอย่าง
#include <iostream>
using namespace std;
class Test {
// ทำให้ operator new เป็น private
void* operator new(size_t size);
int x;
public:
Test() { x = 9; cout << "Constructor is called\n"; }
void display() { cout << "x = " << x << "\n"; }
~Test() { cout << "Destructor is executed\n"; }
};
int main() {
Test t; // OK: stack allocation
t.display();
// Test* p = new Test(); // Compile error: operator new is private
return 0;
}
ผลลัพธ์
Constructor is called x = 9 Destructor is executed
คำอธิบาย
- ประกาศ
void* operator new(size_t size);ในส่วนprivate - ไม่ต้อง define implementation (แค่ประกาศพอ)
- พยายาม
new Test()จะได้ compile error - ยังสร้างออบเจ็กต์บน stack ได้ปกติ (
Test t;) - ยังใช้
newได้ภายใน class (member functions, static methods)
ขยายความ: ห้าม new[] ด้วย
class Test {
void* operator new(size_t size);
void* operator new[](size_t size); // ห้าม array new ด้วย
// ...
};
กรณีต้องการอนุญาตเฉพาะบางการจัดสรร
สามารถ define operator new แบบ custom ได้ เช่น จำกัด alignment, ใช้ memory pool, ฯลฯ