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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With