Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a destructor call a non-const function on a const object?

I searched for the answer to this question and wasn't able to find one. Consider the following code:

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() cannot be called on a const object, so I couldn't do something like foo.do_this(). It would also make sense in some situations to call do_this() outside of the destructor, which is why I don't want to simply include the code in the destructor definition. Because do_this() modifies a member variable, I can't declare it as const.

My question is: will the destructor be able to call do_this() on a const object when the object is destroyed?

I tried it and received no errors, but I want to make sure I'm not causing a memory leak once my program terminates.

like image 967
Mike Borkland Avatar asked Mar 06 '18 16:03

Mike Borkland


People also ask

Can a non-const object call a const function?

const function use cases A const function can be called by either a const or non- const object. Only a non- const object can call a non- const function; a const object cannot call it.

Can you pass a non-const to a const?

For instance, you can pass non-const variables to a function that takes a const argument. The const-ness of the argument just means the function promises not to change it, whether or not you require that promise.

Can const functions only call const functions?

For objects that are declared as const , you can only call constant member functions. The compiler ensures that the constant object is never modified. You can call either constant or non-constant member functions for a non-constant object.

Can a destructor be const?

Destructors cannot be declared const , volatile , const volatile or static . A destructor can be declared virtual or pure virtual . If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares a destructor.


1 Answers

Yes, you can certainly and safely call non-const functions from destructor. Standard explicitly allows this:

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.

like image 160
SergeyA Avatar answered Oct 12 '22 18:10

SergeyA