小编Mik*_*and的帖子

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

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

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当对象被销毁的对象?

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

c++ destructor const language-lawyer

15
推荐指数
1
解决办法
378
查看次数

标签 统计

c++ ×1

const ×1

destructor ×1

language-lawyer ×1