首页 > 解决方案 > 绑定到时间。l/r 值

问题描述

在从这个 S/O答案编译以下代码时,由于绑定问题,我不断收到错误。

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));
           ^~~~~~~~~~~~~~~~~~~

对此进行研究后,我意识到 Bool 向量与普通的 C++ 向量不同。因此,我可以通过将其更改为 int 向量来避免第一个错误。

最后一行的第二个错误更令人困惑。我已经看过这个问题,但我仍然不知道该怎么做。

** 编辑 **

鉴于答案/评论,我觉得这样的事情应该可行,

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

它不是。这似乎会创建带有内存的变量(e 和 f)?

标签: c++binding

解决方案


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

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

您可能应该从函数返回一个对象,而不是一个引用。


编辑:

不,您的新建议也不起作用,原因仍然相同。e一旦函数返回,本地对象就会停止存在,因此对它的引用是没有用的。


推荐阅读