c++ - Is it better to pass-by-value and then move-construct or to pass-by-reference and then copy-construct -
this question has answer here:
- why copy move? 4 answers
in c++11 in constructor, better do:
class { a(std::string str) : mstr(std::move(str)) {} std::string mstr; }
or do
class { a(const std::string& str) : mstr(str) {} std::string mstr; }
in cases can copy elision occur when rvalue passed in constructor?
you should "pass value , move construct" if type's move constructor cheap, , use "pass reference , copy construct" otherwise.
for lvalues
pass value , move construct
you doing 1 copy followed 1 move.
pass reference , copy construct
you doing 1 copy
for rvalues
pass value , move construct
in best case (when rvalue temporary expression) doing no copy/no move, followed move.
in normal case (when rvalue not temporary expression) doing move followed move.
pass reference , copy construct
you doing 1 copy
Comments
Post a Comment