为什么 "auto const&" 不是只读的?
Why is "auto const&" not read-only?
#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;
}
这不仅编译,而且 returns 11.
所以两个问题:
为什么指定为 auto const& 时允许我写入 xb?这不应该编译失败吗?
为什么我不能用 "auto&" 替换 "auto const&" 并让它编译? Clang (6.0) 和 g++ (7.3) 都报错了类似 "non-const lvalue reference of type<...> cannot bind to temporary of type tuple<...>"
的错误信息
谢谢!
您正在获取对 int 的非常量引用元组的 const 引用。然后将该元组分解为两个非常量引用。要使 int 引用常量,您需要使 int 引用常量:
auto const& [xb, yb] = std::tuple<const int&, const int&>(xa, ya);
您正在创建的元组是一个未命名的临时对象,因此您不能将非常量引用绑定到它,即使该引用本身是未命名的。
#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;
}
这不仅编译,而且 returns 11.
所以两个问题:
为什么指定为 auto const& 时允许我写入 xb?这不应该编译失败吗?
为什么我不能用 "auto&" 替换 "auto const&" 并让它编译? Clang (6.0) 和 g++ (7.3) 都报错了类似 "non-const lvalue reference of type<...> cannot bind to temporary of type tuple<...>"
的错误信息
谢谢!
您正在获取对 int 的非常量引用元组的 const 引用。然后将该元组分解为两个非常量引用。要使 int 引用常量,您需要使 int 引用常量:
auto const& [xb, yb] = std::tuple<const int&, const int&>(xa, ya);
您正在创建的元组是一个未命名的临时对象,因此您不能将非常量引用绑定到它,即使该引用本身是未命名的。