I'm fudging around with some code because I think I found a solution to another problem. I'm writing a little test program and I got it to work. But only if I use std::move()
twice in a row.
Here's the example code:
using namespace std;
class Serializable {
public:
virtual string serialize() = 0;
};
class Packet: public Serializable {
string payload;
public:
virtual string serialize() {
return payload;
}
Packet(string payload):
payload(payload) {
cout << "Packet made" << endl;
}
};
class Frame: public Serializable {
unique_ptr<Serializable> packet;
string head;
public:
virtual string serialize() {
return head + packet->serialize();
}
Frame(string head, unique_ptr<Serializable>&& packet):
head(head), packet(move(packet)) { // Second Time
cout << "Frame made" << endl;
}
};
int main()
{
unique_ptr<Serializable> packet = make_unique<Packet>("World!");
Frame frame { "Hello ", move(packet)}; // First Time
cout<<frame.serialize();
return 0;
}
When I remove the "First one" (in main()
), I get this error:
main.cpp:49:29: error: cannot bind rvalue reference of type ‘std::unique_ptr&&’ to lvalue of type ‘std::unique_ptr’
When I remove the other, I get this error:
main.cpp:39:34: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Serializable; _Dp = std::default_delete]’
I understand the one in the constructor, you can't copy a unique_ptr
. But what about the one in main()
? I'm stumped.