为什么"auto const&"不是只读的?

use*_*764 13 c++ const reference auto

#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;
}
Run Code Online (Sandbox Code Playgroud)

这不仅编译,而且返回11.

所以有两个问题:

  1. 为什么在指定为自动const&?时允许写入xb?这不应该编译吗?

  2. 为什么我不能用"auto&"替换"auto const&"并将其编译?Clang(6.0)和g ++(7.3)都抱怨错误消息,例如"类型<...>的非常量左值引用无法绑定到类型元组的临时<...>"

谢谢!

Chr*_*odd 8

  1. 你得到一个const引用的一个非const引用元组的元组.然后,您将该元组分解为两个非const引用.要使int引用为const,需要使int引用为const:

    auto const& [xb, yb] = std::tuple<const int&, const int&>(xa, ya);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您正在创建的元组是一个未命名的临时元素,因此您无法将非const引用绑定到它,即使该引用本身未命名.