[cfe-dev] constexpr difference between gcc and clang

Eli Friedman eli.friedman at gmail.com
Mon Aug 6 20:26:23 PDT 2012


On Mon, Aug 6, 2012 at 6:54 PM, David Wood <dswood at gmail.com> wrote:
> The following compiles fine in macports gcc 4.7, but does not in clang svn
> 161307.  I believe the key is the const reference in combination with the ?:
> operator.
>
> #include <stdexcept>
>
> struct A {
>   constexpr A(int a) : value(a) {}
>
>   constexpr int get() { return value; }
>
> private:
>   int value;
> };
>
> constexpr A someFn(const A& a) {
>   return a.get() == 0 ? throw std::exception() : a;
> }
>
> int main(int argc, char** argv) {
>   constexpr A a(4);
>   static_assert( someFn(a).get() == 4, "error" );
> }
>
> Some digging on the internets reveals
> http://stackoverflow.com/questions/5605142/stdmax-and-stdmin-not-constexpr,
> which seems to point to lvalues, glvalues and memory allocation, although I
> did not follow it very well.  There is also the particularly interesting
> comment :
>
> The C++ committee have suggested that it was intended to be possible for
> function invocation substitution to produce an lvalue referring to a
> temporary. g++ behaves that way, but clang currently implements the standard
> as written.
>
> So, I have two questions.  1) Is the way clang handles this in fact
> conformant to the spec, and gcc is lax? 2) Can someone take another crack at
> explaining why it is that this doesn't work?

>From [expr.const]

A conditional-expression is a core constant expression unless it
involves one of the following as a potentially
evaluated subexpression[...]:

an invocation of a constexpr function with arguments that, when
substituted by function invocation
substitution (7.1.5), do not produce a constant expression

someFn(a) produces the address of the local variable a, which is not a
"constant expression" in the language of [expr.const].

-Eli



More information about the cfe-dev mailing list