Search code examples
c++c++11parameterslvaluervalue

C++ lvalues, rvalues, references, parameters, and performance


So I have a function that needs to take an std::vector as a parameter. I'd like to know the best way to declare the parameter so that the underlying array is not deep-copied, as it could be rather large.

// which should I choose?
void myFunc(std::vector<char>); // 1
void myFunc(std::vector<char>&); // 2
void myFunc(std::vector<char>&&);  // 3
void myFunc(std::vector<char>*) // 4

Which should I choose? Also, I won't be modifying the vector in the function so shouldn't I add const? Should I overload the function and have a combination of these?


Solution

    1. If you are going to make a copy of it inside the function anyway:

      void myFunc(std::vector<char>);
      
    2. If you just want to read the argument without copying it:

      void myFunc(const std::vector<char>&);
      
    3. If you want to modify the original vector passed to the function:

      void myFunc(std::vector<char>&);
      
    4. If you want to optimize for rvalues or if you want to move the argument into the function:

      void myFunc(std::vector<char>&&);
      
    5. If you need to be able to signify an optional argument passed by reference:

      void myFunc(const std::vector<char>*);
      
    6. If you need to pass an optional argument that you want to modify if non-nullptr:

      void myFunc(std::vector<char>*);