C++ Return Value Optimization – Understanding and Returning Temporaries

c++compiler-constructionreturn-value-optimization

Please consider the three functions.

std::string get_a_string()
{
    return "hello";
}

std::string get_a_string1()
{
    return std::string("hello");
}

std::string get_a_string2()
{
    std::string str("hello");
    return str;
}
  1. Will RVO be applied in all the three cases?
  2. Is it OK to return a temporary like in the above code? I believe it is OK since I am returning it by value rather than returning any reference to it.

Any thoughts?

Best Answer

In two first cases RVO optimization will take place. RVO is old feature and most compilers supports it. The last case is so called NRVO (Named RVO). That's relatively new feature of C++. Standard allows, but doesn't require implementation of NRVO (as well as RVO), but some compilers supports it.

You could read more about RVO in Item 20 of Scott Meyers book More Effective C++. 35 New Ways to Improve Your Programs and Designs.

Here is a good article about NRVO in Visual C++ 2005.

Related Question