代码之家  ›  专栏  ›  技术社区  ›  Mario Ishac

为什么一个右值不能绑定到一个非常量左值引用,而不是写入一个临时值没有效果?

  •  3
  • Mario Ishac  · 技术社区  · 8 年前

    我读过 the SO question here 并且理解答案的这一部分:“但是如果你把一个临时引用绑定到一个非常量引用上,你可以一直“永远”地传递它,只是为了让你对对象的操作消失,因为在这个过程中的某个地方,你完全忘记了这是一个临时引用。”

    也就是说,在以下方面:

    #include <iostream>
    
    void modifyValue(int& rValue) {
        rValue++;
    }
    
    int main() {
        modifyValue(9899);
    
        return 0;
    }
    

    如果一个右值可以绑定到一个非常量左值引用,那么可能会进行许多修改,这些修改最终会被丢弃(因为右值是临时的),这是无用的。

    然而,这似乎是定义良好的(写入临时值就像写入任何值一样,生命周期与写入的有效性没有相关性)。

    这是一个完全正确的理由来禁止指定的绑定(即使绑定将被很好地定义),但是,一旦我认为这种被禁止的绑定强制需要转发引用,我的问题就开始形成了。

    对于右值不能绑定到非常量左值引用,是否还有其他原因(即,除了写入临时值之外)?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Richard Hodges    8 年前

    简单的答案是 在大多数情况下 ,向需要可变左值引用的函数传递临时值表示 逻辑错误 ,C++语言正在尽最大努力帮助您避免出错。

    函数声明: void foo(Bar& b) 建议以下叙述:

    foo引用了一个酒吧, b ,它将修改。 乙 因此 输入和输出

    传递一个临时的输出占位符 正常地 比调用返回对象的函数更糟糕的逻辑错误,只会丢弃未经检查的对象。

    例如:

    Bar foo();
    
    void test()
    {
      /*auto x =*/ foo();  // probable logic error - discarding return value unexamined
    }
    

    但是,在这两个版本中,没有问题:

    void foo(Bar&& b)

    foo拥有bar引用的对象的所有权

    void foo(Bar b)

    FOO概念上接受一个条的副本,尽管在许多情况下编译器会决定不需要创建和复制条。

    所以问题是,我们要实现什么?如果我们只需要一个酒吧,我们可以使用 Bar&& b 或 Bar b 版本。

    如果我们想 也许吧 使用临时和 也许吧 使用现有的条,则可能需要两个重载 foo ,因为它们在语义上会有细微的不同:

    void foo(Bar& b);    // I will modify the object referenced by b
    
    void foo(Bar&& b);   // I will *steal* the object referenced by b
    
    void foo(Bar b);   // I will copy your Bar and use mine, thanks
    

    如果我们需要这种可选性,我们可以通过将一个封装在另一个中来创建它:

    void foo(Bar& b)
    {
      auto x = consult_some_value_in(b);
      auto y = from_some_other_source();
      modify_in_some_way(b, x * y);
    }
    
    void foo(Bar&& b)
    {
      // at this point, the caller has lost interest in b, because he passed
      // an rvalue-reference. And you can't do that by accident.
    
      // rvalues always decay into lvalues when named
      // so here we're calling foo(Bar&)
    
      foo(b);   
    
      // b is about to be 'discarded' or destroyed, depending on what happened at the call site
      // so we should at lease use it first
      std::cout << "the result is: " << v.to_string() << std::endl;
    }
    

    有了这些定义,这些都是合法的:

    void test()
    {
      Bar b;
      foo(b);              // call foo(Bar&)
    
      foo(Bar());          // call foo(Bar&&)
    
      foo(std::move(b));   // call foo(Bar&&)
      // at which point we know that since we moved b, we should only assign to it
      // or leave it alone.
    }
    

    好吧,为什么这么在乎?为什么修改一个没有意义的临时文件是一个逻辑错误?

    好吧,想象一下:

    Bar& foo(Bar& b)
    {
      modify(b);
      return b;
    }
    

    我们期待着做这样的事情:

    extern void baz(Bar& b);
    
    Bar b;
    baz(foo(b));
    

    现在假设这可以编译:

    auto& br = foo(Bar());
    
    baz(br); // BOOM! br is now a dangling reference. The Bar no longer exists
    

    因为我们被迫在一个特殊的超负荷 福 作者 福 可以确信这个错误不会在您的代码中发生。