I'm studying std::move semantics and I would like this to be clarified to me:
Say I have:
// Message.h
class Message
{
private:
std::array<uint8_t, BUFFER_SIZE> buffer;
std::queue<Packet> packets;
public:
Message(Packet p)
{
packets.push(std::move(p));
}
}
Now I have:
Packet p;
p << data; // put data into the packet
Message m(p) // wrap the packet in a message.
So this code generates unnecessary copies for my use case, because I will never use p ever again. So I'd like to use the std::move semantics to avoid every copy possible.
What I don't understand is the following:
If I do:
Packet p;
Message m(std::move(p));
While the constructor of Message is still
Message(Packet p) // p is passed by value
p is passed by value, so is it still copied?
Also both of these work:
Packet a;
Packet b;
Message mess1(std::move(a)); // no errors
Message mess2(b); // no errors
But I fail to see the difference. The first one prevents the copy (even with that constructor) and the seconds allows the copy? Or not?
While If I modify the constructor so that:
Message(Packet&& c)
Am I right to assume that in this case no copies will ever be made and I'm basically forcing the programmer to use std::move(a) otherwise the program won't compile?
I tried to do multiple tests with objects and try to understand the difference but I couldn't.
&&andstd::moveno move construction actually gets performed, and no unnecessary temporary object is created eitherMessageis defined, it would need to copy the data stored inPacketanyway. So takeconst Packet&- that at least would avoid copyingPacketitself. Your design wouldn't benefit from move semantics.Packet const&is a reference. APacket&is a reference. APacket&&is a reference. They're all references. Each variant has some slight contractual differences, because they're for different use cases. A reference is like an alias that refers to the same object, but doesn't manage the object's lifetime (with the exception of lifetime extension, which does manage the object's lifetime). Pass by value makes a copy. Pass by reference does not make a copy.