问题
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.)
回答1:
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.
回答2:
In [optional]:
A program that necessitates the instantiation of template optional for a reference type, or for possibly cv-qualified types
in_place_t
ornullopt_t
is ill-formed.
There is no std::optional<T&>
. For now, you'll have to use std::optional<std::reference_wrapper<T>>
.
来源:https://stackoverflow.com/questions/40382838/why-gcc-rejects-stdoptional-for-references