Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...