Move semantics can be useful when the compiler cannot use RVO and NRVO. But in which case can't the compiler use these features?
Compilers often perform Named Return Value Optimization (NRVO) in such cases, but it is not guaranteed.
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.
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.
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.
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();
}
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