I understand copy elision well. But I can't find out what happens when copy elision is not possible. In those situations, if available, is the move constructor or move assignment operator guaranteed to be called? Are there any situations where moving will not be possible and the code will fallback to copy constructor or assignment?
class X {
//A heavy class expensive to copy
//Moving ctor
X(X&& other) {
//...
}
//Moving assignment op
X& operator=(X&& other) {
//...
return *this;
}
//...
}
//Most compilers can't do copy elision
X test(int i) {
X n1;
X n2;
if (i > 0) {
return n1;
} else {
return n2;
}
}
//What happens here?
int main() {
//Is move construction guaranteed?
X x1 = test(-1);
X x2;
//Is move assignment guaranteed?
x2 = test(10);
return 0;
}
My understanding, so far, is this.
- Compiler first attempts to do copy and move elision.
- If that's not possible then it tries to apply move constructor or move assignment if available.
- Only if a move ctor or assignment is not available then it degrades down to using copying.
Is that accurate? I was looking for an authoritative source to confirm my observations.