user4222907
user4222907

Reputation:

Using std::move when passing lvalue

If in my code, I have declared a variable (for example string) and want to pass to some function so my vector would add that value. Do I always need to do this(using the std::move), considering I do not need that passed variable anymore?

Void add(string s){
    my_vector.push_back(move(s));
}

I do know that I can simply pass an rvalue but consider if I needed to declare the string first (making it an rvalue) and then adding it to the vector.

Because I don’t want to copy the variable and then push back to my vector

Upvotes: 2

Views: 875

Answers (2)

Xavier Lamorlette
Xavier Lamorlette

Reputation: 1302

Depending on what you intend to do with your add method and how you plan to use it, you should consider using a universal reference: you declare the s argument as a rvalue reference and then:

  • if the calling argument is a lvalue, s will be a lvalue reference;
  • if the calling argument is a rvalue, s will be a rvalue reference.

Hence, the following code will benefit from move semantic optimisation whenever possible:

void add(string && s) {
    my_vector.push_back(s);
}

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92241

If you want the string to be moved, you have to say so. Otherwise it will be copied.

But unless this is a hot spot in your application, the difference might be small enough not to be noticed.

For a std::string in particular, the major implementations use a Small String Optimization, where short strings (typically 10-20 bytes) will be stored inside the string object to save on heap allocations. In that case moving and copying will do the same thing for the short strings.

Upvotes: 1

Related Questions