Say a given class A is defined with a public copy constructor and a private move constructor. If a function f returns an object of type A, and f is used to initialize a local instance of variable of type A, then by default (since the value returned is a rvalue) the compiler will try to use the move constructor. I believed it is sensible to expect the compiler to use the copy constructor once it detects that the move constructor is private, however to my surprise I received a compiler error stating that the move constructor is private. My question is as follows, given the following code:
#include<iostream>
using namespace std;
class A
{
friend A f();
public:
A(const A&) { cout << "copy\n"; }
private:
A() {}
A(A&&) { cout << "move\n"; }
};
A f()
{
A a;
return a;
}
int main()
{
A a = f();
}
How can I change the code (without changing A or f) so that I could initialize the variable in main using the copy constructor?
I would change the class since it’s not sensible.
Alternatively derive from the class or wrap it.
If you just want a quick hack you can do
then do
Disclaimer: code not touched by compiler’s hands.