如何在 C++ 中限制对象的动态分配?

c++server side programmingprogramming

在本教程中,我们将讨论一个程序,以了解如何在 C++ 中限制对象的动态分配。

为此,我们将 new 操作符函数设为私有,这样就无法使用它动态创建对象。

示例

#include <iostream>
using namespace std;
class Test{
   //将 new 操作符设为私有
   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

相关文章