且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何= delete on destructor防止分配?

更新时间:2023-12-02 22:39:58

自动存储持续时间(即局部变量)的变量的析构函数需要当变量的生命周期结束时运行。如果没有可访问的析构函数,编译器拒绝编译分配这样一个变量的代码。

The destructor of a variable with automatic storage duration (i.e. a local variable) would need to run when the variable's lifetime ends. If there is no accessible destructor the compiler refuses to compile the code that allocates such a variable.

基本上,堆栈分配方式)和***存储分配是与局部变量构造函数/析构函数调用总是成对,而与***存储分配,你可以构造一个对象,而不会破坏它。因此,通过防止访问析构函数,你的代码使得不可能分配类型的局部变量(如果构造函数运行析构函数也必须运行,但没有析构函数,所以程序被拒绝)。

Basically the distinction between "stack allocation" (an inaccurate choice of term by the way) and free store allocation is that with local variables constructor/destructor calls always come in pairs, whereas with free store allocation you can construct an object without ever destructing it. Therefore by preventing access to the destructor your code makes it impossible to allocate a local variable of the type (if the constructor runs the destructor must also run, but there is no destructor so the program is rejected).