【问题标题】:Binding to tempories. l/r values绑定到时间。 l/r 值
【发布时间】:2018-09-17 14:57:31
【问题描述】:

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

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

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

** 编辑 **

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

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

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

【问题讨论】:

  • matrix_row(m.at(x)) 是一个临时的,由向量元素构成。您正在尝试返回一个左值引用 - 它不能引用一个临时的。由于 vector&lt;bool&gt; 不起作用的完全相同的原因,它不起作用 - 您正在返回一个代理对象,而不是对实际元素的引用。
  • @IgorTandetnik 谢谢你的评论,真的很有帮助!据我了解,我现在需要创建一个分配了一些内存的变量,然后在函数中返回它?
  • 按值返回matrix_row,或返回std::vector&lt;bool&gt;引用。你不能同时拥有它
  • @IgorTandetnik 谢谢,所以我删除了函数定义中的&amp;,现在出现以下错误,ld: can't open output file for writing: m./m, errno=2 for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) any idea?
  • 我的猜测是,您尝试构建的可执行文件仍在运行,可能来自之前的实验。

标签: c++ binding


【解决方案1】:

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

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

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


编辑:

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

【讨论】:

  • 感谢您的回答,真的很有帮助!我一直在试图弄清楚如何避免这种情况,我想也许如果我先创建一个变量然后返回它,它可能会被分配一些内存(如在我的编辑中),不幸的是,这不起作用。您能否详细说明如何 避免这种情况?非常感谢
  • @AngusTheMan 新尝试有同样的问题。您返回对函数结束后不存在的对象的引用。正如我所说,您可能应该返回一个对象,而不是一个引用。
  • 谢谢,所以我删除了函数定义中的&amp;,现在出现以下错误,ld: can't open output file for writing: m./m, errno=2 for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) 任何想法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2014-11-25
  • 2018-05-19
  • 1970-01-01
  • 2021-09-21
  • 2019-06-06
  • 2019-04-27
相关资源
最近更新 更多