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; }
Any thoughts?
In the context of the C++ programming language, return value optimization (RVO) is a compiler optimization that involves eliminating the temporary object created to hold a function's return value. RVO is allowed to change the observable behaviour of the resulting program by the C++ standard.
> Note also that C doesn't have return-value-optimization, hence all your struct-returning functions will cause a call to memcpy (won't happen when compiled in C++ mode of course).
the NRVO (Named Return Value Optimization)
Compilers often perform Named Return Value Optimization (NRVO) in such cases, but it is not guaranteed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With