constexpr std::optional reset
Asked Answered
D

1

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?

Doggy answered 20/12, 2018 at 21:25 Comment(1)
If that were true, no assignment operator could be marked constexpr. std::optional has several such assignment operators.Doggy
R
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.

Replication answered 20/12, 2018 at 22:11 Comment(6)
Is there a paper to make optionals functions constexpr now that we have P1330?Searle
@Searle Not that I'm aware of - want to write it?Replication
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)?Celebrated
@Celebrated Yes. And can't use any kind of reinterpret_cast in constexpr.Replication
@Searle Alright, now there is.Replication
We don't deserve you Barry. You're amazing :)Doggy

© 2022 - 2024 — McMap. All rights reserved.