如何= delete on destructor防止分配? [英] How does =delete on destructor prevents allocation?

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

问题描述

在此 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 on destructor防止分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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