用 return 语句结束析构函数是否安全?

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

在我的双向链表 class 中,我正在编写我的析构函数,这是我的代码:

DLinkedList::~DLinkedList() {
    if (head==NULL) {
        return;
    }

    // Other code
}

return; 语句结束析构函数是否安全?

我知道我可以用 return; 语句结束我的 void 函数,但这是一个析构函数。

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.

析构函数与voidreturn类型的函数没有太大区别,除了析构函数会自动执行1每当class的生命周期结束了。

如果应该停止析构函数的执行,您可以使用 return;,就像您对任何其他函数所做的那样。


1)这同样适用于构造函数顺便说一句。

是的,可以用return结束析构函数的执行。

是。

从这个意义上说,析构函数体的行为很像 returns void 的函数,除了基础和成员仍然会被销毁,即使你 return 早(因为无论如何,这从不依赖于析构函数体的内容。

遵守以下规则:

[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. [..]

是的,它不仅安全。标准 明确地 指出它是等价的,它明确地将析构函数作为空 return 语句的一个用例。

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

(重点是我加的。)