levidone
levidone

Reputation: 345

Is it safe to end a destructor with a return statement?

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.

Upvotes: 26

Views: 2504

Answers (4)

Damon
Damon

Reputation: 70206

Yes, and it is not only safe. The standard explicitly states that it is equivalent, and it explicitly gives destructors as one use case for empty return statements.

6.6.3 The return statement [stmt.return]
1 A function returns to its caller by the return statement.
2 A return statement with neither an expression nor a braced-init-list can be used only in functions that do not return a value, that is, a function with the return type cv void, a constructor (12.1), or a destructor (12.4).
[...]
Flowing off the end of a function is equivalent to a return with no value

(Emphasis was added by me.)

Upvotes: 1

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Is it safe to end a destructor with return; statement? I know that I can end my void functions with a return; 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.

Upvotes: 27

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385305

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 the return statement.

[stmt.return]/2: The expr-or-braced-init-list of a return statement is called its operand. A return 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: [..] A return 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. [..]

Upvotes: 12

gsamaras
gsamaras

Reputation: 73424

Yes, it's OK to end the execution of a destructor with a return.

Upvotes: 7

Related Questions