I am scratching my head on std::optional
which, according to the docs, shouldn't have a constexpr
assignment operator.
However, when I try this snippet in gcc-8.1, it compiles and works just fine:
constexpr std::optional<int> foo() {
std::optional<int> bar = 3;
bar = 1337;
return bar;
}
constexpr auto z = foo();
Is there something I am missing?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With