constexpr构造函数是否允许返回语句?

Kal*_*ish 6 c++ gcc constructor constexpr c++14

本页所述,constexpr构造函数体的复合语句,如果没有删除也没有默认,必须满足constexpr函数体的约束,也就是说,它可以包含除以下内容之外的任何语句:

  • 一个asm声明
  • 一份goto声明
  • a- tryblock
  • 非文字类型或静态或线程存储持续时间的变量的定义,或者不执行初始化的定义

似乎标准不限制return可能出现的语句数量,而在C++ 11中,只允许一个.

现在,请考虑以下代码:

class Thing
{
    public:
        // Shouldn't this constructor be fine under both C++11 and C++14?
        constexpr Thing ( )
        {
            return;
        }
};

int main ( )
{
    Thing a_nice_thing;
}
Run Code Online (Sandbox Code Playgroud)

Clang(3.5和-std = c ++ 14)编译得很好,但是GCC(4.9.1和-std = c ++ 14)没有抱怨:

constexpr构造函数没有空体

但是,如果它改变了:

class Thing
{
    public:
        // This constructor is fine under both C++11 and C++14
        constexpr Thing ( )
        {
            static_assert( __cplusplus > 1 , "static_assert isn't the right mechanism to test this, since it wasn't available at earlier versions of the language" );
        }
};

int main ( )
{
    Thing a_nice_thing;
}
Run Code Online (Sandbox Code Playgroud)

然后它在两个编译器下编译得很好.

由于海湾合作委员会抱怨建设者的身体不是空的,在后一种情况下难道不应该抱怨吗?这种行为是GCC中的一个错误吗?constexpr构造函数是否允许返回语句?

注意:单个return陈述是否真的值得这不是这个问题的范围,虽然有趣并且可能值得另一个.return出于样式原因,我将单个语句放在主体为空的构造函数上.

T.C*_*.C. 5

GCC目前不支持 C++ 14的版本constexpr,所以即使-std=c++14你仍然得到C++ 11的版本constexpr.

constexpr构造函数体的C++ 11限制是(§7.1.5[dcl.constexpr]/p4):

功能体复合声明仅包含

  • 空语句,
  • static_assert申述
  • typedef声明和别名声明,没有定义类或枚举,
  • 使用声明,
  • 使用指令 ;

(还有很多其他限制;我将报价限制在与问题相关的报价上.)

returnconstexpr在C++ 11中,构造函数中不允许使用语句,而static_asserts是.