why can temporary objects be bound to const refere

2019-08-14 16:25发布

Source of question:

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);

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

I guess I also don't fully understand the scope of existence for temporary objects created in an argument.

1条回答
家丑人穷心不美
2楼-- · 2019-08-14 17:01

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.

Say you make a call.

foo(10);

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);

it's fair to implement foo as:

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

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.
}

From 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, ...

and from 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.

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 compilers have allowed binding of non-const references to temporary objects but it is not sanctioned by the standard.

查看更多
登录 后发表回答