Search code examples
c++move-semantics

Is it a good idea to use `std::move` with a function that receives const ref?


Here's a snippet that compiles and works:

#include <iostream>
#include <string>

void print_str(const std::string& str) {
    std::cout << str << '\n';
}

int main() {
    std::string str = "Hello world";
    print_str(std::move(str));
}

Godbolt

As far as I understand, std::move has no effect here.

Two questions:

  • Is it correct that std::move isn't harmful here, and just has no effect?
  • Would it be considered good practice to use it anyway? If I don't control print_str, and don't need str after the call, one may say that std::move will have a positive effect if at some point print_str will be changed to get std::string by value.

Solution

  • You're correct, move has no effect here, and whether to use this is completely opinion-based.

    • On one hand, it can indeed improve performance if/when print_str is changed this way. It also expresses intent to not use str again.

    • On the other hand, it might be a WTF moment for a future reader of your code. Also if you have code after that that (incorrectly) reads from str after the no-op move, if will break when print_str gets updated this way.

    Personally, I'd do this only if:

    • print_str looks like it should take the argument by value but currently doesn't (e.g. a setter that should move the string into the class, but currently copies it)
    • I'm in a short function where it's hard to accidentally reuse the string after the move.