Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a local object rvalue reference,right or wrong?

Tags:

c++

c++11

I see once return a local object,the compiler will take the return value optimization.(RVO,NRVO).

The part of the Standard blessing the RVO goes on to say that if the conditions for the RVO are met, but compilers choose not to perform copy elision, the object being returned must be treated as an rvalue.

So we just write code like this:

Widget makeWidget() 
{
 Widget w;
 …
 return w;//never use std::move(w);
}

I never see somebody write code like this:

Widget&& makeWidget()
{
 Widget w;
 …
 return std::move(w); 
}

I know that returns an lvalue reference of local object is always wrong. So, returns an rvalue reference of local object is also wrong?

like image 377
Ron Tang Avatar asked Mar 09 '15 11:03

Ron Tang


People also ask

Is return value a rvalue?

Typically rvalues are temporary objects that exist on the stack as the result of a function call or other operation. Returning a value from a function will turn that value into an rvalue.

What are rvalue references good for?

Rvalue references is a small technical extension to the C++ language. Rvalue references allow programmers to avoid logically unnecessary copying and to provide perfect forwarding functions. They are primarily meant to aid in the design of higer performance and more robust libraries.

How do you use rvalue reference?

If the function argument is an rvalue, the compiler deduces the argument to be an rvalue reference. For example, assume you pass an rvalue reference to an object of type X to a template function that takes type T&& as its parameter. Template argument deduction deduces T to be X , so the parameter has type X&& .

Can lvalue reference bind rvalue?

An lvalue const reference can bind to an lvalue or to an rvalue. The syntax for a reference to an rvalue of type T is written as T&& . An rvalue reference refers to a movable value—a value whose contents we don't need to preserve after we've used it (for example, a temporary).


1 Answers

Returning a reference to a local automatic variable is always wrong. The variable will be destroyed when the function returns, so any use of the reference will give undefined behaviour.

It makes no difference whether it's an rvalue or lvalue reference.

like image 79
Mike Seymour Avatar answered Oct 20 '22 12:10

Mike Seymour