析构函数是否被视为 const 函数?
考虑一下
class Foo
{
public:
Foo(){}
~Foo(){}
void NonConstBar() {}
void ConstBar() const {}
};
int main()
{
const Foo* pFoo = new Foo();
pFoo->ConstBar(); //No error
pFoo->NonConstBar(); //Compile error about non const function being invoked
delete pFoo; //No error
return 0;
}
在主函数中,我调用 Foo 的 const 和 非 const 函数
尝试调用任何非 const 函数会在 Visual 中产生错误像这样的工作室
错误 C2662: 'Foo::NonConstBar' : 无法将 'this' 指针从 'const Foo' 转换为 'Foo &'
但删除 pFoo
不会发出任何此类错误。 delete 语句必然会调用没有 const 修饰符的 Foo 类的析构函数。析构函数还可以调用其他非 const 成员函数。那么它到底是不是一个const函数呢?或者 const 指针上的删除是一个特殊的例外吗?
Consider this
class Foo
{
public:
Foo(){}
~Foo(){}
void NonConstBar() {}
void ConstBar() const {}
};
int main()
{
const Foo* pFoo = new Foo();
pFoo->ConstBar(); //No error
pFoo->NonConstBar(); //Compile error about non const function being invoked
delete pFoo; //No error
return 0;
}
In the main function I am calling both const and non const functions of Foo
Trying to call any non const function yields an error in Visual Studio like so
error C2662: 'Foo::NonConstBar' : cannot convert 'this' pointer from 'const Foo' to 'Foo &'
But delete pFoo
doesn't issue any such error. The delete statement is bound to call the destructor of Foo class which doesn't have a const modifier. The destructor is also allowed to call other non const member functions. So is it a const function or not ? Or is delete on a const pointer a special exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过常量指针删除对象。在 C++11 中,您还可以通过常量迭代器擦除容器元素。所以是的,从某种意义上说,析构函数总是“恒定的”。
一旦析构函数被调用,该对象就不再存在。我认为一个不存在的对象是否可变的问题是没有意义的。
You can delete objects thorough constant pointers. In C++11, you can an also erase container elements through const-iterators. So yes, in a sense the destructor is always "constant".
Once the destructor is invoked, the object has ceased to exist. I suppose the question of whether a non-existing object is mutable or not is moot.
对象的生命周期在析构函数被调用时结束(对于所有者/封闭范围),而不是在析构函数返回时结束。
因此,我认为删除常量没有任何问题。当你调用delete的时候它就已经消失了。
否则删除常量对象将需要 const_cast。
The lifetime of an object ends (for the owner/enclosing scope) as soon as the destructor is invoked, not when the destructor returns.
Therefore I don't see any problem deleting constants. It's already gone for you when you call delete.
Otherwise deleting constant objects would require a const_cast.