In C++ if we define a class destructor as:
~Foo(){ return; }
upon calling this destructor will the object of Foo
be destroyed or does explicitly returning from the destructor mean that we don't ever want to destroy it.
I want to make it so that a certain object is destroyed only through another objects destructor i.e. only when the other object is ready to be destroyed.
Example:
class Class1{ ... Class2* myClass2; ... }; Class1::~Class1(){ myClass2->status = FINISHED; delete myClass2; } Class2::~Class2(){ if (status != FINISHED) return; }
I searched online and couldn't seem to find an answer to my question. I've also tried figuring it out myself by going through some code step by step with a debugger but can't get a conclusive result.
Declaring destructorsDo not return a value (or void ). Cannot be declared as const , volatile , or static . However, they can be invoked for the destruction of objects declared as const , volatile , or static .
While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3.
This does not give any meaning to the return type of the destructor itself. An explicit destructor call expression may or may not be a function call expression (it is if the type is a class with a destructor, it isn't if the type has trivial destruction because it is a non-class type).
When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used. Calling destructors is sometimes important, for example, if destructor has code to release resources like closing files.
No, you can't prevent the object from being destroyed by return statement, it just means the execution of the dtor's body will end at that point. After that it still will be destroyed (including its members and bases), and the memory still will be deallocated.
You migth throw exception.
Class2::~Class2() noexcept(false) { if (status != FINISHED) throw some_exception(); } Class1::~Class1() { myClass2->status = FINISHED; try { delete myClass2; } catch (some_exception& e) { // what should we do now? } }
Note it's a terrible idea indeed. You'd better to reconsider the design, I'm sure there must be a better one. Throwing exception won't stop the destruction of its bases and members, just make it possible to get the process result of Class2
's dtor. And what could be done with it is still not clear.
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