📌  相关文章
📜  如何限制C++中对象的动态分配?

📅  最后修改于: 2021-05-26 00:05:41             🧑  作者: Mango

C++编程语言允许自动(或堆栈分配)和动态分配的对象。在Java和C#中,必须使用new动态分配所有对象。
出于运行时效率的考虑,C++支持堆栈分配的对象。基于堆栈的对象由C++编译器隐式管理。它们超出范围时将销毁它们,并且必须使用delete运算符手动释放动态分配的对象,否则会发生内存泄漏。 C++不支持Java和C#等语言使用的自动垃圾收集方法。

我们如何通过C++中的“测试”类实现以下行为?

Test* t = new Test; // should produce compile time error
Test t;    // OK 

的想法是使新的运算符函数保持私有状态,以便不能调用new。请参阅以下程序。无法使用new创建’Test’类的对象,因为新的运算符函数在’Test’中是私有的。如果取消注释main()的第二行,程序将产生编译时错误。

#include 
using namespace std;
  
// Objects of Test can not be dynamically allocated
class Test
{
    // Notice this, new operator function is 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()
{
    // Uncommenting following line would cause a compile time error.
    // Test* obj=new Test();
    Test t;          // Ok, object is allocated at compile time
    t.display();
    return 0;
} // object goes out of scope, destructor will be called

输出:

Constructor is called
x = 9
Destructor is executed

参考:
C++ Bjarne Stroustrup的设计和演变

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”