我搜索了此问题的答案,但找不到。考虑以下代码:
struct Foo
{
int *bar;
Foo(int barValue) : bar(new int(barValue)) {}
~Foo() { do_this(); }
void do_this() { delete bar; bar = nullptr; }
};
int main()
{
const Foo foo(7);
}
不能在
do_this()
对象上调用const
,因此我无法执行类似foo.do_this()
的操作。在某些情况下,在析构函数之外调用do_this()
也很有意义,这就是为什么我不想在析构函数定义中简单地包含代码。因为do_this()
修改了一个成员变量,所以我不能将其声明为const
。我的问题是:销毁对象时销毁该析构函数是否可以对其调用
do_this()
?我尝试过但没有收到任何错误,但是我想确保一旦程序终止,我不会造成内存泄漏。
最佳答案
是的,您当然可以从析构函数中安全地调用非const函数。标准明确允许: