【发布时间】:2018-10-02 02:14:50
【问题描述】:
#include <tuple>
int main()
{
int xa = 1;
int ya = 2;
auto const& [xb, yb] = std::tuple<int&, int&>(xa, ya);
xb = 9; // Shouldn't this be read-only?
return xa + ya;
}
这不仅编译,而且返回 11。
那么两个问题:
当 xb 指定为 auto const& 时,为什么我可以写入?这不应该编译失败吗?
为什么我不能用“auto&”替换“auto const&”并让它编译? Clang (6.0) 和 g++ (7.3) 都抱怨错误消息,例如“类型<...> 的非 const 左值引用无法绑定到类型为 tuple<...> 的临时值”
谢谢!
【问题讨论】:
-
同意这是重复的,但这是一个更简单的例子。
-
万岁更多扭曲的初始化规则...
-
是否最好将另一个问题标记为该问题的副本,因为这个问题更加清晰?
-
@Galik 是的,如果这个答案很好的话。
-
@liliscent:人们可以忽略这一点,但他们很少这样做。问题质量很重要。
标签: c++ reference constants auto