为什么不能将临时作为参数发送到C++中的函数?

Tho*_*mas 3 c++ reference

这有效:

class Foo {};
void external_function(Foo&);
void f() {
  Foo b;                                                                                                                                         
  external_function(b);                                                                                                                          
}
Run Code Online (Sandbox Code Playgroud)

这不是:

class Foo {};
void external_function(Foo&);
void f() {
  external_function(Foo());
}
Run Code Online (Sandbox Code Playgroud)

Clang说:

aac.cc:3:6: note: candidate function not viable: no known conversion from 'Derived' to 'Base &' for 1st argument;
Run Code Online (Sandbox Code Playgroud)

GCC实际上更有帮助:

aac.cc:7:30: error: invalid initialisation of non-const reference of type ‘Base&’ from an rvalue of type ‘Derived’
Run Code Online (Sandbox Code Playgroud)

Herb Sutter(http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/)表示非const引用不能用于rvalues,这在他的例子中是有意义的,但不在我的,因为对象在external_function()调用的持续时间内存在,不是吗?

我知道如何使它发挥作用; 只需创建一个命名对象,使其不是右值(如上所述),或使用const ref.但我想知道为什么不允许这样做,因为它对我来说似乎是安全的.

jua*_*nza 9

您不能将任何类型的临时绑定到非const左值引用.这里的继承只是一种分心.

struct Foo{};

void bar(Foo&) {}
void cbar(const Foo&) {}

int main()
{
  Foo f;
  bar(f);      // OK
  bar(Foo());  // ERROR
  cbar(Foo()); // OK: const reference binds to temporary
}
Run Code Online (Sandbox Code Playgroud)

至于最终" 为什么?" ,它被认为容易出错,允许通过左值参考修改右值.引自" The C++ Programming Language,Fourth Edition "§7.7.1

对变量的引用和对常量的引用是有区别的,因为为变量引入临时变量会非常容易出错; 对变量的赋值将成为 - 很快就会消失 - 临时的赋值.对常量的引用不存在这样的问题......