In my doubly-linked list class, I am coding my destructor and this is my code:
DLinkedList::~DLinkedList() {
if (head==NULL) {
return;
}
// Other code
}
Is it safe to end a destructor with a return;
statement?
I know that I can end my void
functions with a return;
statement, but this is a destructor.
Properties of Destructor: The destructor does not have arguments. It has no return type not even void.
However, in your current implementation you're actually returning a shallow copy of NodeContainer. Once your copy goes out of scope its destructor is called, which deallocates its memory, which in this case is the original memory of your member, effectively making your member invalid.
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.
The best way to not call a particular destructor is to not create an instance of that object to begin with. Failing that, take the code you don't want to run out of the destructor.
Is it safe to end a destructor with
return;
statement? I know that I can end myvoid
functions with areturn;
statement, but this is a destructor.
There's not much difference of a destructor function from a function with void
return type, besides the destructor function is executed automatically1 whenever the class's lifetime ends.
You use return;
if the execution of the destructor function should be stopped, as you do with any other function.
1)The same applies for constructor functions BTW.
Yes.
In this sense, the destructor body acts much like a function that returns void
, except that the bases and members will still be destroyed even if you return
early (since this never relied on the contents of the destructor body anyway).
Observe the following rules:
[special]/1
: The default constructor ([class.default.ctor]
), copy constructor, move constructor ([class.copy.ctor]
), copy assignment operator, move assignment operator ([class.copy.assign]
), and destructor ([class.dtor]
) are special member functions. [..]
[stmt.return]/1
: A function returns to its caller by thereturn
statement.
[stmt.return]/2
: The expr-or-braced-init-list of areturn
statement is called its operand. Areturn
statement with no operand shall be used only in a function whose return type is cv void, a constructor, or a destructor. [..]
[class.dtor]/9
: [..] Areturn
statement ([stmt.return]
) in a destructor might not directly return to the caller; before transferring control to the caller, the destructors for the members and bases are called. [..]
Yes, it's OK to end the execution of a destructor with a return
.
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