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));
}
As far as I understand, std::move
has no effect here.
Two questions:
std::move
isn't harmful here, and just has no effect?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.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)