1

I need to make a member function that has an argument of std::vector<int> and uses the move semantics to steal the guts of it and place to a different std::vector<int> that is a member of class T.

class T {

std::vector<int> vec; 

public: 

void setVec(std::vector<int> vec_){ vec = std::move(vec_); }

}

Now my question is; What is the different and implications of having the following interfaces for setVec and which one should be used?

1 : void setVec(std::vector<int> vec_)

2 : void setVec(std::vector<int>& vec_)

3 : void setVec(std::vector<int>&& vec_)

ATK
  • 1,296
  • 10
  • 26
  • 1
    Take your time to read the dupe, there's quite a lot of information there. If you have a question that's not directly addressed there, then edit the question. – cigien Oct 26 '20 at 14:12
  • For a data sink parameter such as this situation, my team would use option 1. That puts the least burden on the caller, although we'd probably implement this one as a `std::swap` rather than `std::move`, but that's splitting hairs. – Eljay Oct 26 '20 at 14:13
  • @cigien: The 'dupe' contains a lot of info on what the move semantics does and definition of r-value and l-value. That is all fine, however, I am more specifically questioning the impact of the suggested function interfaces and whether some `move` semantics would just end up being copies, like what happens if you had a `const` in the argument – ATK Oct 26 '20 at 14:15
  • Did you read the second answer? It's an expansion of the accepted answer by the same user, and goes into a *lot* of detail, and addresses your concerns quite clearly, I think. – cigien Oct 26 '20 at 14:17
  • It's a mouthful, but `template >, bool> = true> void setVec(T&& vec_){ vec = std::forward(vec_); }` is the forwarding reference approach. – NathanOliver Oct 26 '20 at 14:18

0 Answers0