Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

c++ - 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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...