I see this subject was discussed in StackOverflow, but I could not find the right answer.
I've been using C++ for many years, and I am still in doubt about how to write a simple setter method for a class which needs to set the value of a string.
class Content
{
public:
void setXml(??? xml)
{
xml_ = xml;
}
private:
std::string xml_;
};
There can be two possible usages: one when I want to copy the original string, the other when I want to move it, ie:
std::string xml = getXml();
Content content;
content.setXml(xml); // copy
Or:
content.setXml(std::move(xml)); // move
Or:
content.setXml(getXML()); // move
Do I need to define two separate setter methods in class Content, like this?
void setXml(const std::string& xml)
{
xml_ = xml;
}
void setXml(std::string&& xml)
{
xml_ = std::move(xml);
}
Or use perfect forwarding?
template<class String>
void setXml(String&& xml)
{
xml_ = std::forward<String&&>(xml);
}
My aim is to avoid unnecessary copying/allocation of the string (as it can be very long) for strings which can be moved, however for string that must be copied, I need to allow copying functionality as well.
Am I right to say that, in this case, copy elision is not going to happen, as it is only in case of returning objects from a function?
std::stringis in itself already a container. Do you really need to wrap a container inside another container? Perhaps you could rework your design so that you don't need a container-container, and therefore not need a "setter" (which in the majority of cases tend to be a sign of bad design, IMO).