I am trying to understand move semantics, rvalue references, std::move
, etc. I have been trying to figure out, by searching through various questions on this site, why passing a const std::string &name
+ _name(name)
is less recommended than a std::string name
+ _name(std::move(name))
if a copy is needed.
If I understand correctly, the following requires a single copy (through the constructor) plus a move (from the temporary to the member):
Dog::Dog(std::string name) : _name(std::move(name)) {}
The alternative (and old-fashioned) way is to pass it by reference and copy it (from the reference to the member):
Dog::Dog(const std::string &name) : _name(name) {}
If the first method requires a copy and move both, and the second method only requires a single copy, how can the first method be preferred and, in some cases, faster?
Aucun commentaire:
Enregistrer un commentaire