Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why GCC rejects std::optional for references?

std::optional<int&> xx; just doesn't compile for the latest gcc-7.0.0 snapshot. Does the C++17 standard include std::optional for references? And why if it doesn't? (The implementation with pointers in a dedicated specialization whould cause no problems i guess.)

like image 467
Vahagn Avatar asked Nov 02 '16 14:11

Vahagn


People also ask

Can STD optional contain a reference?

Update: optional is a container for values. Like other containers ( vector , for example) it is not designed to contain references. If you want an optional reference, use a pointer, or if you indeed need an interface with a similar syntax to std::optional , create a small (and trivial) wrapper for pointers.

What is the use of std :: optional?

std::optional contains the object within itself, depending on where it is stored (stack/data/heap) std::optional makes a copy of the contained object. Monadic functions will be added in C++23 to improve the abstraction in our code by removing the needs of writing boilerplate code.

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.

Does STD optional allocate?

What's more, std::optional doesn't need to allocate any memory on the free store. std::optional is a part of C++ vocabulary types along with std::any , std::variant and std::string_view .


1 Answers

Because optional, as standardized in C++17, does not permit reference types. This was excluded by design.

There are two reasons for this. The first is that, structurally speaking, an optional<T&> is equivalent to a T*. They may have different interfaces, but they do the same thing.

The second thing is that there was effectively no consensus by the standards committee on questions of exactly how optional<T&> should behave.

Consider the following:

optional<T&> ot = ...;
T t = ...;
ot = t;

What should that last line do? Is it taking the object being referenced by ot and copy-assign to it, such that *ot == t? Or should it rebind the stored reference itself, such that ot.get() == &t? Worse, will it do different things based on whether ot was engaged or not before the assignment?

Some people will expect it to do one thing, and some people will expect it to do the other. So no matter which side you pick, somebody is going to be confused.

If you had used a T* instead, it would be quite clear which happens:

T* pt = ...;
T t = ...;
pt = t;   //Compile error. Be more specific.
*pt = t;  //Assign to pointed-to object.
pt = &t;  //Change pointer.
like image 61
Nicol Bolas Avatar answered Sep 28 '22 17:09

Nicol Bolas