析构函数是一种特殊的成员函数,它不接受任何参数,也没有返回类型:几乎所有的 C++ 书籍中都提到了这一点。但是,在 libstd++ 库中,它使用以下内容来测试类型是否可破坏,
struct __do_is_destructible_impl
{
template<typename _Tp, typename _U = decltype(declval<_Tp&>().~_Tp())>
static true_type __test(int);
template<typename>
static false_type __test(...);
};
Gnu g++ 会显示带有 typeid void 的 _U,那么,析构函数会返回一个类型吗?请专家解释一下 c++ 标准对此有何规定。
最佳答案
请注意,您正在考虑的代码正在检查显式析构函数调用表达式的返回类型。这对析构函数本身的返回类型没有任何意义。
显式析构函数调用表达式可能是也可能不是函数调用表达式(如果类型是具有析构函数的类,则不是,如果类型具有平凡的破坏,因为它是非类类型)。 [expr.call]
中描述了函数调用,它具有以下用于显式析构函数调用的特殊规则:
If the postfix-expression designates a destructor, the type of the function call expression is
void
; otherwise, the type of the function call expression is the return type of the statically chosen function (i.e., ignoring thevirtual
keyword), even if the type of the function actually called is different. This return type shall be an object type, a reference type orcv
void
.
这不适用于伪析构函数调用,如 [expr.pseudo]
(伪析构函数调用)中所述,其中说明如下:
The use of a pseudo-destructor-name after a dot
.
or arrow->
operator represents the destructor for the non-class type denoted by type-name or decltype-specifier. The result shall only be used as the operand for the function call operator()
, and the result of such a call has typevoid
. The only effect is the evaluation of the postfix-expression before the dot or arrow.
如您所见,在这两种情况下都没有到达使函数返回类型和函数调用表达式类型相同的子句。因此,表达式的类型为 void
,即使(特殊成员)函数根本没有返回类型。
关于C++ 析构函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55214616/