C++ return value optimization(RVO)

| 分类 C++  | 标签 C++_std 

It was recognized long ago that the “copying” version of function can avoid the need to copy the local variable by constructing it in the memory alloted for the function’s return value. This is known as the return value optimization (RVO), and it’s been expressly blessed by the C++ Standard for as long as there’s been one.

Widget makeWidget()
{
Widget w;
...
return std::move(w); // move w into return value
//return w;         // copy w into return value
}

As the above code shows, w is a local variable and using return w will not cause a copy construction because of the RVO. In fact, compilers may elide the copying (or moving) of a local object in a function that returns by value if (1) the type of the local object is the same as that returned by the function and (2) the local object is what’s being returned. For return std::move(w);, what’s being returned here isn’t the local object w, it’s a reference to w—the result of std::move(w). Returning a reference to a local object doesn’t satisfy the conditions required for the RVO, so compilers must move w into the function’s return value location.

And even the compiler didn’t elide the copy operation of the local variable, the local object being returned must be treated as an rvalue. So when RVO is permitted, either copy elision takes place or std::move is implicitly applied to local objects being returned.

We can draw a conclusion that when RVO is permitted, don’t apply the std::move() or std::forward() to the local variable.


上一篇     下一篇