std::move vs. compiler optimization

c++, compiler-optimization, move-semantics

Solution

It's definitely not the same. For once `T &&` can only bind to rvalues, while `T const &` can bind both to rvalues and to lvalues. Second, `T const &` does not permit any move optimizations. If you "probably want to make a copy of `t`", then `T &&` allows you to actually make a move-copy of `t`, which is potentially more efficient.

Example:

void foo(std::string const & s) { std::string local(s); /* ... */ }

int main()
{
    std::string a("hello");
    foo(a);
}

In this code, the string buffer containing `"hello"` must exist twice, once in the body of `main`, and another time in the body of `foo`. By contrast, if you used rvalue references and `std::move(a)`, the very same string buffer can be "moved around" and only needs to be allocated and populated one single time.

As @Alon points out, the right idiom is in fact passing-by-value:

void foo(std::string local) { /* same as above */ }

int main()
{
    std::string a("hello");
    foo(std::move(a));
}

Problem

For example: ``` void f(T&& t); // probably making a copy of t void g() { T t; // do something with t f(std::move(t)); // probably something else not using "t" } ``` Is `void f(T const& t)` equivalent in this case because any good compiler will produce the same code? I'm interested in >= VC10 and >= GCC 4.6 if this matters. EDIT: Based on the answers, I'd like to elaborate the question a bit: Comparing `rvalue-reference` and `pass-by-value` approaches, it's so easy to forgot to use `std::move` in `pass-by-value`. Can compiler still check that no more changes are made to the variable and eliminate an unnecessary copy? `rvalue-reference` approach makes only optimized version "implicit", e.g. `f(T())`, and requires the user to explicitly specify other cases, like `f(std::move(t))` or to explicitly make a copy `f(T(t));` if the user isn't done with `t` instance. So, in this optimization-concerned light, is `rvalue-reference` approach considered good?

Original source

Related problems