Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding return value optimization and returning temporaries - C++

Tags:

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?

like image 277
Navaneeth K N Avatar asked Sep 08 '09 14:09

Navaneeth K N


People also ask

How does return value optimization work?

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.

Does C have return value optimization?

> 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).

What is NRVO?

the NRVO (Named Return Value Optimization)

Is NRVO guaranteed?

Compilers often perform Named Return Value Optimization (NRVO) in such cases, but it is not guaranteed.


1 Answers

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.

like image 119
Kirill V. Lyadvinsky Avatar answered Oct 06 '22 17:10

Kirill V. Lyadvinsky