析构函数上的= delete如何防止堆栈分配? [英] How does =delete on destructor prevent stack allocation?

查看:90
本文介绍了析构函数上的= delete如何防止堆栈分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此 SO问题中,该结构阻止了堆栈分配

In this SO question is stated that this construct prevents stack allocation of instance.

class FS_Only {
    ~FS_Only() = delete;  // disallow stack allocation
};

我的问题是,它如何防止分配?我了解,无法显式或隐式删除此实例。但是我认为,这将分别导致内存泄漏或运行时错误。

My question is, how does it prevents allocation? I understand, that is not possible to delete this instance, either explicitly or implicitly. But I think, that would lead to memory leak or run time error, respectively.

编译器是否足够聪明以解决此问题并引发编译器错误?还有为什么为什么需要这个呢?

Are compilers smart enough to sort this out and raise compiler error? Also why would one need this?

推荐答案

具有自动存储持续时间的变量(即本地变量)的析构函数将需要在变量的生存期结束时运行。如果没有可访问的析构函数,则编译器将拒绝编译分配此类变量的代码。

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).

这篇关于析构函数上的= delete如何防止堆栈分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆