Quick Q: Return a local object rvalue reference, right or wrong?

Quick A: Wrong!

Recently on SO:

Return a local object rvalue reference,right or wrong?

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?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.