且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么GCC拒绝std :: optional作为参考?

更新时间:2022-06-13 23:10:33

因为C ++ 17中的标准optional不允许引用类型.这是有意排除的.

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

有两个原因.首先,从结构上来讲,optional<T&>等同于T*.它们可能具有不同的接口,但是它们执行相同的操作.

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.

第二件事是,标准委员会实际上没有就optional<T&>应该如何表现的问题达成共识.

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

请考虑以下内容:

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

最后一行应该做什么?它是否正在使用ot所引用的对象并对其进行复制分配,例如*ot == t?还是应该重新绑定存储的引用本身,例如ot.get() == &t?更糟糕的是,根据作业之前是否参与了ot ,它会做不同的事情吗?

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.

如果您使用的是T*,则很清楚会发生什么情况:

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.