为什么临时对象可以绑定到 const 引用?

why can temporary objects be bound to const reference?

The only failing case is passing parameters by non-const reference, since temporary variable couldn't be bound to it.

void DrawLine(const Vector& v1, const Vector& v2);

如果对象是临时对象,为什么引用 const 会对临时对象的生命周期产生任何影响?

我想我也没有完全理解参数中创建的临时对象的存在范围。

If the object is temporary, why would making the reference const have any effect on the lifetime of the temporary object?

在当前上下文中,问题不是对象的生命周期,而是您是否可以修改它。

假设你打个电话。

foo(10);

调用中保存值10的对象不应该被函数修改。如果foo的接口是:

void foo(int& ref);

foo 实施为:

是公平的
void foo(int& ref)
{
   ref = 20;
}

鉴于调用 foo(10),这将是一个问题。如果 foo 使用 const&.

不会有问题
void foo(int const& ref)
{
   ref = 20; // Not allowed.
}

来自C++11 Standard, Temporary Objects/1

Temporaries of class type are created in various contexts: binding a reference to a prvalue ([dcl.init.ref]), returning a prvalue ([stmt.return]), a conversion that creates a prvalue, ...

来自C++11 Standard, References/5.2

-- Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be const), or the reference shall be an rvalue reference.

临时对象只能绑定到对纯右值的引用。这种引用的类型必须是 const 合格的左值引用或右值引用。

MS Visual Studio 编译器允许将非 const 引用绑定到临时对象,但标准未批准。