Is it safe to end a destructor with a return statement?
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
.