且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-10 05:39:35

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

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

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

In the present context, the issue is not the lifetime of the object but whether you can modify it.

假设你打电话.

foo(10);

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

The object that holds the value 10 in the call should not be modified by the function. If the interface of foo is:

void foo(int& ref);

foo 实现为:

void foo(int& ref)
{
   ref = 20;
}

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

That would be a problem given the call foo(10). It won't be a problem if foo uses a const&.

void foo(int const& ref)
{
   ref = 20; // Not allowed.
}

来自 C++11 标准,临时对象/1一个>

类类型的临时文件在各种上下文中创建:绑定对纯右值的引用([dcl.init.ref]),返回一个纯右值([stmt.return]),一个创建纯右值的转换,...​​

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 标准,References/5.2:

-- 否则,引用应为对非易失性 const 类型的左值引用(即 cv1 应为 const),或者引用应为右值引用.

-- 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 限定的左值引用或右值引用.

A temporary can only bind to a reference to a prvalue. The type of such a reference must be a const qualified lvalue reference or a rvalue references.

MS Visual Studio 编译器允许将非const 引用绑定到临时对象,但它不受标准的认可.

MS Visual Studio compilers have allowed binding of non-const references to temporary objects but it is not sanctioned by the standard.