c++ - 析构函数可以在 const 对象上调用非常量函数吗?

标签 c++ constants language-lawyer destructor

我搜索了这个问题的答案,但没有找到。考虑以下代码:

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

我的问题是:当对象被销毁时,析构函数能否在 const 对象上调用 do_this()

我试过了,没有收到任何错误,但我想确保我的程序终止后不会导致内存泄漏。

最佳答案

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

15.4/2 A destructor is used to destroy objects of its class type. The address of a destructor shall not be taken. A destructor can be invoked for a const, volatile or const volatile object. const and volatile semantics ([dcl.type.cv]) are not applied on an object under destruction. They stop being in effect when the destructor for the most derived object starts.

关于c++ - 析构函数可以在 const 对象上调用非常量函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49135839/

相关文章:

c++ - 避免在多线程套接字应用程序中重复使用相同的 fd 号

c++ - 如何在编译时隐藏DLL文件中的字符串?

c++默认在switch语句中不起作用

c++ - 为什么静态方法会覆盖基类非静态方法?

c++ - 基本类型的复制/分配

c++ - 定义外联成员模板函数

c++ - 在 Visual Studio 2017 上使用 VC++ 2015 工具链时缺少 ATL header

c++ - 观察者模式中的 Const-correct 通知程序

c++ - 外部数组定义

c++ - 专用于 const char * 的模板也会接受 char * 吗?