Full Example (N) RVO

I read about (N) RVO and would like a full description of the script. I hope this question will be useful to other C ++ users to clarify their ideas.

Assume this scenario:

string get_string() { string x("racecar"); //work on x... return x; } string a( get_string() ); string b = get_string(); 

Ignore the semantics of moving C ++ 11 for a moment.

  • If there is no (N) RVO, how many constructors / assignments / destructors will be executed? (indicate which objects they belong to)
  • What will change if (N) RVO is applied?
  • Finally, how the situation is changing in C ++ 11, assuming that std::string supports semantics entry.
+6
source share
1 answer

1) Inside get_string one string object (x) will be constructed using a constructor that accepts const char* .

2) When the function returns, the string built inside will be copied to a temporary string object in the call space.

3) A temporary copy will be built on a .

4) See 1

5) See 2

6) See 3, but the copy will go to b

With RVO 2 and 5, you can eliminate it by building a temporary function inside using an invisible link. With further copying (not RVO), 3 and 6 can be eliminated. Thus, we leave us two constructs using the const char* constructor.

With the C ++ 11 relocation semantics, the situation does not change at all if the compiler was good enough to execute all copies. If copying is not performed, then 2, 3, 5, and 6 still exist, but become moving, not copies. However, unlike copying, these steps are not an optional optimization. The appropriate compiler should execute them, assuming that it has not yet executed a copy.

+6
source

Source: https://habr.com/ru/post/928173/


All Articles