As explained in this page, the compound statement of the body of a constexpr
constructor, if it is not deleted nor defaulted, must satisfy the constraints for the body of a constexpr
function, that is, it may contain any statements except:
- an
asm
declaration - a
goto
statement - a
try
-block - a definition of a variable of non-literal type or of static or thread storage duration or for which no initialization is performed
It seems that the standard does not restrict the number of return
statements that may appear, whereas, in C++11, only one was allowed.
Now, consider the following code:
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;
}
Clang (3.5 with -std=c++14) compiles it fine, but GCC (4.9.1 with -std=c++14) does not, complaining:
constexpr constructor does not have empty body
However, if it is changed:
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;
}
Then it compiles fine under both compilers.
Since GCC complains about the constructor's body not being empty, shouldn't it also complain in the later case? Is this behavior a bug in GCC? Is the return statement allowed on constexpr constructors?
Note: whether a single return
statement is really worth is not the scope of this question, although interesting and perhaps worth another one. I put single return
statements on constructors whose body is empty, for style reasons.