析构函数可以在const对象上调用非const函数吗?

Mik*_*and 15 c++ destructor const language-lawyer

我搜索了这个问题的答案,却找不到答案.请考虑以下代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

do_this()不能在一个const对象上调用,所以我做不了类似的事情foo.do_this().在某些情况下do_this(),在析构函数之外调用也是有意义的,这就是为什么我不想简单地在析构函数定义中包含代码.因为do_this()修改成员变量,我不能将其声明为const.

我的问题是:将析构函数可以调用do_this()一个在const当对象被销毁的对象?

我尝试了它并没有收到任何错误,但我想确保一旦我的程序终止,我不会导致内存泄漏.

Ser*_*eyA 13

是的,您当然可以安全地从析构函数中调用非const函数.标准明确允许这样:

15.4/2析构函数用于销毁其类类型的对象.不得采用析构函数的地址.可以为const,volatile或const volatile对象调用析构函数.const和volatile语义([dcl.type.cv])不应用于销毁下的对象.当最派生对象的析构函数启动时,它们将停止生效.