析构函数是否被视为const函数? [英] Is a destructor considered a const function?

查看:245
本文介绍了析构函数是否被视为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;
}

在主函数中,我同时调用 const Foo

In the main function I am calling both const and non const functions of Foo

尝试调用任何非const函数会在Visual Studio中产生错误,如下所示

Trying to call any non const function yields an error in Visual Studio like so

错误C2662:'Foo :: NonConstBar':无法将'this'指针从'const Foo'转换为'Foo&'

但是删除pFoo 不会发出任何此类错误。 delete语句必须调用没有常量修饰符的 Foo 类的析构函数。还允许析构函数调用其他非const成员函数。那么它是一个const函数吗?还是在 const指针上删除是一个特殊的例外?

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?

推荐答案

您可以通过常量指针删除对象。在C ++ 11中,您还可以通过const-iterators删除容器元素。所以是的,从某种意义上说,析构函数始终是常量。

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.

这篇关于析构函数是否被视为const函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆