It seems like this is a bug in gcc. I just tried in clang-6.0 and the compilation fails with the expected error. Also, the standard doesn't mention any constexpr
overload for the assignment operator, thus I'll report this bug to gcc bugtracker.
Link to the bug report
Edit:
It turned out that this is not a bug in gcc, but a mistake in the standard:
I don't understand how the code snippet can work in a constexpr context when the current c++17 standard doesn't specify any constexpr assignment operator.
That's true, but the standard is broken.
All implementations define the assignment operator as defaulted, and so the compiler makes it constexpr.
In fact the P0602R3 proposal is relevant, because it would require implementations to define the operator as defaulted (in order to be trivial) and so the compiler is always going to make it constexpr for std::optional.
I've raised this with the standards committee.
You can read more about it in the bug report.
constexpr auto z = foo()
compile also? – Arminconstexpr
. (And it's expected to apply retroactively to C++17.) – Gereld