Say I have this class:
class Message
{
public:
using Payload = std::map<std::string, boost::any>;
Message(int id, Payload payload)
: id_(id),
payload_(std::move(payload))
{}
int id() const {return id_;}
const Payload& payload() const {return payload_;}
private:
int id_;
Payload payload_;
};
where Payload
could potentially be large and expensive to copy.
I would like to give users of this Message
class the opportunity to move the payload instead of having to copy it. What would be the best way to go about doing this?
I can think of the following ways:
Add a
Payload& payload()
overload which returns a mutable reference. Users can then do:Payload mine = std::move(message.payload())
Stop pretending that I'm encapsulating
payload_
and just make it a public member.Provide a
takePayload
member function:Payload takePayload() {return std::move(payload_);}
Provide this alternate member function:
void move(Payload& dest) {dest = std::move(payload_);}
(Courtesy of Tavian Barnes) Provide a
payload
getter overload that uses a ref-qualifier:const Payload& payload() const {return payload_;}
Payload payload() && {return std::move(payload_);}
Alternative #3 seems to be what's done in std::future::get, overload (1).
Any advice on what would be the best alternative (or yet another solution) would be appreciated.
EDIT: Here's some background on what I'm trying to accomplish. In my real life work, this Message class is part of some communications middleware, and contains a bunch of other meta data that the user may or may not be interested in. I had thought that the user might want to move the payload data to his or her own data structures and discard the original Message object after receiving it.