Why does GCC reject std :: optional for links?

std::optional<int&> xx; just doesn't compile for the last gcc-7.0.0 snapshot. Does the C ++ 17 standard std::optional for links? And why, if it is not? (An implementation with pointers in a special specialization that does not cause any problems, I think.)

+5
source share
2 answers

Because optional , as standardized in C ++ 17, does not allow the use of reference types. This was ruled out by design.

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

Secondly, the standards committee did not receive a unanimous opinion on how optional<T&> should behave.

Consider the following:

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

What should this last line do? Does the object referenced by ot accept and assign a copy to it, for example *ot == t ? Or should he ot.get() == &t saved link, for example ot.get() == &t ? Worse, will it do different things based on whether ot busy or not before the appointment?

Some people expect him to do one thing, and some expect him to do another. So no matter which side you choose, someone will be confused.

If you used T* , it would be perfectly clear what happens:

 T* pt = ...; T t = ...; pt = t; //Compile error. Be more specific. *pt = t; //Assign to pointed-to object. pt = &t; //Change pointer. 
+5
source

In [optional]:

A program requiring the creation of an instance of a template, optional for a reference type, or, possibly, for types with qualifications cv in_place_t or nullopt_t , is poorly formed.

No std::optional<T&> . For now, you need to use std::optional<std::reference_wrapper<T>> .

+2
source

Source: https://habr.com/ru/post/1259164/


All Articles