1
void foo(const std::string& str);
foo(std::move(localstr));

If I know that I won't use this string anymore, will I have any gain by moving it if the function expects reference?

In general, there are so many advices now on the web for using parameters by value to be able to gain from moves, but I can't really find any practical usage of this so far. For me it seems that I still better declare my functions as const or non-const references.

Bruice
  • 543
  • 3
  • 11
  • it depends, what is `foo` doing with the string? how big is the string? please provide a [mre] – Alan Birtles Mar 03 '21 at 23:06
  • 2
    The code does not do any moving. `std::move` is just a cast to an rvalue reference and `const std::string&` can bind to an rvalue refence. Nothing is moved or changed. `localstr` will be unchanged at the end. – Richard Critten Mar 03 '21 at 23:17
  • 1
    Does this answer your question? [What is move semantics?](https://stackoverflow.com/questions/3106110/what-is-move-semantics) – Richard Critten Mar 03 '21 at 23:39

1 Answers1

0

If the variable is a std string, moving it there will do nothing until the API changes.

If the variable can be converted to a std string, moving it could be more efficient if there is an rvalue conversion constructor.

std move is a cast to an rvalue reference, and does not actually move. It gives permission for code to move it, but it only happens if that offer is taken up.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524