Please take a look at this silly function, which should only illustrate the problem and a simplification of the real code:
struct A;
A create(bool first){
A f(21), s(42);
if(first)
return f;
else
return s;
}
I understand, that because it is not clear which object will be returned during the compilation, we cannot expect return value optimization (RVO) to be always performed.
However, one maybe could expect RVO to be performed in 50% of the cases (assuming uniform distribution for true
/false
due to lack of further information): just decide for which case RVO (first==true
or first==false
) should be performed and apply it for this parameter-value, accepting that in the other case the copy constructor must be called.
Yet this "partial RVO" is not the case for all compilers I can get my hands on (see live with gcc, clang and MSVC) - in both cases (i.e. first==true
or first==false
) the copy-constructor is used and not omitted.
Is there something, that renders the "partial RVO" in the above case invalid or is this an unlikely case of missed optimization by all compilers?
Complete program:
#include <iostream>
struct A{
int val;
A(int val_):val(val_){}
A(const A&o):val(o.val){
std::cout<<"copying: "<<val<<"\n";
}
};
A create(bool first){
A f(21), s(42);
if(first)
return f;
else
return s;
}
int main(){
std::cout<<"With true: ";
create(true);
std::cout<<"With false: ";
create(false);
}