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?
optional is required to not use dynamic allocation. If an optional contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place.
(since C++17) The class template std::optional manages an optional contained value, i.e. a value that may or may not be present. A common use case for optional is the return value of a function that may fail.
Raymond Chen. October 4th, 20216 0. C++17 introduced std::optional<T> which lets you augment the values of a type T with a bonus value known as std::nullopt which semantically represents the absence of a value. A std::optional which holds the value std::nullopt is known as empty. The basic operations on std::optional ...
std::exchange was introduced in the C++ standard library in C++14 under the header <utility> . Its name suggests that it's a general-purpose and useful function, and its template prototype working with any type confirms this impression.
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.
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