ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อทำความเข้าใจวิธีจำกัดการจัดสรรวัตถุแบบไดนามิกใน C++
สำหรับสิ่งนี้ เราจะรักษาฟังก์ชันโอเปอเรเตอร์ใหม่ให้เป็นส่วนตัว เพื่อไม่ให้สร้างอ็อบเจ็กต์โดยใช้ไดนามิก
ตัวอย่าง
#include <iostream> using namespace std; class Test{ //making new operator 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; t.display(); return 0; }
ผลลัพธ์
Constructor is called x = 9 Destructor is executed