析构函数可以在 const 对象上调用非常量函数吗?
Can a destructor call a non-const function on a const object?
我搜索了这个问题的答案,但没有找到。考虑以下代码:
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()
?
我试过了,没有收到任何错误,但我想确保我的程序终止后不会导致内存泄漏。
是的,您当然可以从析构函数中安全地调用 non-const 函数。标准明确允许这样做:
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.
我搜索了这个问题的答案,但没有找到。考虑以下代码:
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()
?
我试过了,没有收到任何错误,但我想确保我的程序终止后不会导致内存泄漏。
是的,您当然可以从析构函数中安全地调用 non-const 函数。标准明确允许这样做:
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.