I'm using VS Code to compile and debug with g++ in Linux.
Needed includes and usings:
#include <string>
#include <iostream>
using namespace std;
Here is my class which is moveable:
class A {
public:
A(const string& strA) : strA(strA) {}
A(const A& a) : A(a.strA) {
}
A(A&& a) : A(a.strA) {
a.strA = "";
}
string strA;
};
Example function that returns an instance of A:
A RetA() {
A a("a");
A b("bha");
string ex;
cin >> ex;
a.strA += ex;
return ex == "123" ? a : b;
}
And here is the simple main:
int main() {
A a(RetA());
return 0;
}
And returning value in the RetA function is copied, not moved. Why?
On the other hand, if we use "explicitly if" instead of ternary operator in the RetA function:
A RetA() {
A a("a");
A b("bha");
string ex;
cin >> ex;
a.strA += ex;
if (ex == "123")
return a;
return b;
}
Then it is moved, not copied. This is already expected behaviour. But it is strange that move operation doesn't work with ternary operator. Should it be like that or is it a bug or something for VS Code etc?