11

I was reviewing the interface for the C++-17 std::optional class template and noticed that the reset and assignment from nullopt are not marked as constexpr.

Was this an oversight or is there a reason that this operation cannot be marked constexpr?

apmccartney
  • 743
  • 8
  • 16
  • 3
    If that were true, no assignment operator could be marked constexpr. `std::optional` has several such assignment operators. – apmccartney Dec 20 '18 at 21:31

1 Answers1

10

There was a reason, which was that [expr.const] had previously forbid:

an assignment expression or invocation of an assignment operator ([class.copy]) that would change the active member of a union;

That restriction no longer exists as a result of P1330: Changing the active member of a union inside constexpr, which makes all of these things much easier to implement (the paper literally just removes the bullet point I quoted above).

The reason that optional's copy and move assignment (but none of the other assignments) were constexpr was because they can just be defaulted for trivial types.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • Is there a paper to make `optional`s functions constexpr now that we have P1330? – Rakete1111 Dec 21 '18 at 20:50
  • @Rakete1111 Not that I'm aware of - want to write it? – Barry Dec 28 '18 at 19:32
  • Follow ups: With that, it's possible to implement an entirely `constexpr` `std::optional`, correct? And why does the standard implementation use a `union` in the first place (e.g. in favor of `std::aligned_storage` or just raw bytes)? – m8mble Dec 12 '20 at 17:05
  • 1
    @m8mble Yes. And can't use any kind of `reinterpret_cast` in constexpr. – Barry Dec 12 '20 at 17:26
  • 2
    @Rakete1111 Alright, [now there is](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2231r0.html). – Barry Dec 12 '20 at 17:26
  • We don't deserve you Barry. You're amazing :) – apmccartney Dec 13 '20 at 18:16