A constant expression cannot access a mutable sub-object. This is in expr.const#4.8
An object or reference is usable in constant expressions if it is ... a non-mutable subobject ...
And there is a nice question about it. (Both recent GCC and Clang properly reject the example from there).
But is there any restrictions on using objects (both starting and ending their lifetime) with mutable fields in constexpr functions? Please consider the example:
struct S {
mutable int i = 2;
};
auto f = []{
constexpr S s;
s.i = 3;
return s.i;
};
// ok everywhere
int x = f();
// error in GCC
constexpr int y = f();
Here the initialization of y succeeds in Clang, but fails in GCC with the error:
in 'constexpr' expansion of 'f.<lambda()>()'
error: mutable 'S::i' is not usable in a constant expression
Online demo: https://gcc.godbolt.org/z/qbfY6jfbe
On the one side, mutable subobject is indeed used. But on the other side, it shall behave as normal not-const object, which is allowed inside constexpr functions.
Which compiler is right here?