Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::optional assignment operator in a constexpr context

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?

like image 439
ProXicT Avatar asked Aug 19 '18 19:08

ProXicT


Video Answer


1 Answers

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.

like image 160
ProXicT Avatar answered Sep 23 '22 18:09

ProXicT