Is a destructor considered a const function?

2019-01-23 12:48发布

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?

2条回答
Explosion°爆炸
2楼-- · 2019-01-23 13:08

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.

查看更多
看我几分像从前
3楼-- · 2019-01-23 13:22

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.

查看更多
登录 后发表回答