代码之家  ›  专栏  ›  技术社区  ›  AngusTheMan

对临时工有约束力。l/r值

  •  1
  • AngusTheMan  · 技术社区  · 6 年前

    Whist从这个S/O编译以下代码 answer ,由于绑定问题,我不断出现错误。

    class my_matrix {
      std::vector<std::vector<bool> >m;
    public:
      my_matrix(unsigned int x, unsigned int y) {
        m.resize(x, std::vector<bool>(y,false));
      }
      class matrix_row {
        std::vector<bool>& row;
      public:
        matrix_row(std::vector<bool>& r) : row(r) {
        }
        bool& operator[](unsigned int y) {
          return row.at(y);
        }
      };
      matrix_row& operator[](unsigned int x) {
        return matrix_row(m.at(x));
      }
    };
    // Example usage
    my_matrix mm(100,100);
    mm[10][10] = true;
    

    这是报告

    m.cpp:16:14: error: non-const lvalue reference to type 'bool' cannot bind to a
          temporary of type 'reference' (aka '__bit_reference<std::__1::vector<bool,
          std::__1::allocator<bool> > >')
          return row.at(y);
                 ^~~~~~~~~
    m.cpp:20:12: error: non-const lvalue reference to type 'my_matrix::matrix_row'
          cannot bind to a temporary of type 'my_matrix::matrix_row'
        return matrix_row(m.at(x));
               ^~~~~~~~~~~~~~~~~~~
    

    question 但我还是不知道该怎么办。

    **编辑**

    matrix_row& operator[](unsigned int x) {
        std::vector<int> e = m.at(x);
        matrix_row f = matrix_row(e);
        return f;
    

    它没有。这似乎是用内存创建变量(e和f)?

    1 回复  |  直到 6 年前
        1
  •  0
  •   eerorika    6 年前

    您正在尝试将非常量左值引用绑定到右值。那是不可能的。

    请注意,尽管将常量引用或非常量r值引用绑定到r值在语法上是正确的,但这是错误的,因为一旦函数返回,您创建的临时对象将停止存在,因此拥有对临时对象的引用是没有用的。


    编辑:

    不,你的新建议也行不通,原因还是一样的。本地对象 e 一旦函数返回就停止退出,因此引用它是没有用的。