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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…