为什么GCC拒绝std :: optional作为参考? [英] Why GCC rejects std::optional for references?

查看:290
本文介绍了为什么GCC拒绝std :: optional作为参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::optional<int&> xx;只是不为最新的gcc-7.0.0快照编译. C ++ 17标准是否包含std::optional供参考?那为什么不呢? (在专门的专业领域中使用指针的实现,我猜不会造成任何问题.)

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

推荐答案

因为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.

这篇关于为什么GCC拒绝std :: optional作为参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆