Issue
If I want to define a method like a setter for a std::vector member (or movable object) I can do it like this:
void set(const std::vector<int>& v) { _v = v; }
But also I need to add
void set(std::vector<int>&& v) { _v = std::move(v); }
Right? Is it always best to define both in order to handle temporaries that can be move? So all setters will be doubled? Thanks.
Solution
If you know the type has an efficient move constructor (which std::vector<int>
does), then you can just take by value and move from the argument:
void set(std::vector<int> v) { _v = std::move(v); }
That way, when called with an lvalue it will be copied, but when called with an rvalue it will be moved.
Answered By - Artyer Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.