Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr std::optional reset

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?

like image 859
apmccartney Avatar asked Dec 20 '18 21:12

apmccartney


People also ask

Does STD optional allocate memory?

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.

What is std :: optional C++?

(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.

What is std :: Nullopt?

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 ...

What is STD exchange?

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.


1 Answers

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.

like image 66
Barry Avatar answered Sep 30 '22 07:09

Barry