Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can't a compiler use RVO or NRVO?

Tags:

c++

move

Move semantics can be useful when the compiler cannot use RVO and NRVO. But in which case can't the compiler use these features?

like image 288
Guillaume Paris Avatar asked May 09 '12 19:05

Guillaume Paris


People also ask

Is return value optimization guaranteed?

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

Does Const prevent RVO?

There is no way for RVO optimization to break the promise of a const , so there's no problem: RVO can be performed. However, move semantics is affected by the const . It effectively disables move semantics, that is, calls of a T(T&&) constructor or move assignment operator.

How does RVO work c++?

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.

How RVO works?

The neat thing about RVO is that it makes returning objects free. It works via allocating memory for the to-be-returned object in the caller's stack frame. The returning function then uses that memory as if it was in its own frame without the programmer knowing / caring.


1 Answers

The answer is that it is compiler and situation dependent. E.g. control flow branching might confuse optimizers. Wikipedia give this example:

#include <string>
std::string f(bool cond = false) {
  std::string first("first");
  std::string second("second");
  // the function may return one of two named objects
  // depending on its argument. RVO might not be applied
  return cond ? first : second;
}

int main() {
  std::string result = f();
}
like image 130
TemplateRex Avatar answered Oct 17 '22 13:10

TemplateRex