C++ 析构函数返回类型

标签 c++ c++11 language-lawyer destructor decltype

析构函数是一种特殊的成员函数,它不接受任何参数,也没有返回类型:几乎所有的 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 the virtual keyword), even if the type of the function actually called is different. This return type shall be an object type, a reference type or cv 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 type void. The only effect is the evaluation of the postfix-expression before the dot or arrow.

如您所见,在这两种情况下都没有到达使函数返回类型和函数调用表达式类型相同的子句。因此,表达式的类型为 void,即使(特殊成员)函数根本没有返回类型。

关于C++ 析构函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55214616/

相关文章:

c++ - 在 std 命名空间 : any guarantees? 中定义的友好类

c++ - std::make_array<size_t> 来自 signed int

c - 函数原型(prototype)中的顶级 volatile 或 restrict 是否重要?

C++ 奇怪的 memcpy 行为

c++ - (C++) 数组中的特定值

c++ - 将 std::shuffle 与自定义随机数生成器一起使用?

c++ - 什么是 C++ 中未评估的上下文?

c++ - OpenGL顶点数组不渲染

c++ - for 语句后的大括号

c++ - 如何对齐 std::array 包含的数据?