Can I make the code below work without copying the object b?
#include <iostream>
using namespace std;
class A{
public:
A() = default;
A(const A& a) { cout << "copy ctor\n"; }
A(A&& a) { cout << "move ctor\n"; }
A& operator=(const A& a) { cout << "copy\n"; return *this;}
A& operator=(A&& a) { cout << "move\n"; return *this;}
};
A Gen() {
A x;
return x;
}
int main() {
bool cached = true;
const A b;
const A& a = cached ? b : Gen();
}
It seems like when cached
is true, then the copy ctor is called.
*Edit: in the real code, the class A is kinda big, so I want to avoid copying.
*Edit 2: I made b
as constant, to clarify the intent.