tistCoder tistCoder - 12 days ago 9
C++ Question

Should I always implement a move-semantic for functions and methods?

Does it make sense to overload

set(/*args*/)
with move?:

class Person {
private:

//properties
std::string name;
std::string adress;
std::string favmovie;

public:

//set without operator=
void set(const std::string& name, const std::string& adress, const std::string& favmovie) {
this->name = name;
this->adress = adress;
this->favmovie = favmovie;

return;
}

//set without operator=
void set(std::string&& name, std::string&& adress, std::string&& favmovie) {
this->name = name;
this->adress = adress;
this->favmovie = favmovie;

return;
}

Person(const std::string& name, const std::string& adress, const std::string& favmovie)
: name(name), adress(adress), favmovie(favmovie) {

}

Person(std::string&& name, std::string&& adress, std::string&& favmovie)
: name(name), adress(adress), favmovie(favmovie) {

}

};


It feels like copy and paste with a little bit of an edit but I'm doing this to every function or method I have so far to make them high-performing. Is this a good practice? I mean it stops your computer from copying rvalues, doesn't it?

qxz qxz
Answer

A const reference, like the parameter in your first function, will bind to rvalues without any copying; the parameter will just be a reference to the rvalue. This only works for const references, not mutable references.

Therefore, there would be no purpose or performance benefit to have a second version of the function that takes an rvalue reference.