When passing objects to functions there is the choice to pass arguments either by value or by const&. Especially when the object is possibly expensive to create and it is internally mutated or used to initialize another object the recommendation is to pass the object by value. For example:
class Foo {
std::vector<std::string> d_strings;
public:
Foo(std::vector<std::string> strings): d_strings(std::move(strings)) {}
// ...
};
The conventional approach would be to declare the strings parameter as std::vector<std::string> const& and copy the argument. The value argument to the constructor above also needs to be copied!
Why is it preferable to pass by value rather than pass by const&?
Aucun commentaire:
Enregistrer un commentaire