Is accessing a static constexpr member from a placement new a constant expression?

Viewed 105

To clarify, is the following program well-formed?

#include <new>
char foo[32];
struct bar {
        static constexpr int foobar = 42;
};

int main() 
{
        auto p = new (foo) bar();
        static_assert(p->foobar == 42);
}

gcc and msvc accept, but clang rejects with the error read of non-constexpr variable 'p' is not allowed in a constant expression, who is right?

1 Answers

If you change it to:

auto constexpr p = new (foo) bar();

Then the clang error message becomes clearer:

<source>:12:24: error: constexpr variable 'p' must be initialized by a constant expression
        auto constexpr p = new (foo) bar();
                       ^   ~~~~~~~~~~~~~~~
<source>:12:28: note: dynamic memory allocation is not permitted in constant expressions until C++20
        auto constexpr p = new (foo) bar();
                           ^

So the answer depends on the C++ language version.

Related