Is this correct usage of C++ ‘move’ semantics? [duplicate]

A reference is still a reference. In the same way you cannot return a reference to a local in C++03 (or you get UB), you can’t in C++0x. You’ll end up with a reference to a dead object; it just happens to be an rvalue reference. So this is wrong:

std::vector<T>&& doSomething() const
{
    std::vector<T> local;

    return local; // oops
    return std::move(local); // also oops
}

You should just do what you saw in number two:

// okay, return by-value 
std::vector<T> doSomething() const
{
    std::vector<T> local;

    return local; // exactly the same as:
    return std::move(local); // move-construct value
}

Variables local to a function are temporary when you return, so there’s no need to change any of your code. The return type is the thing responsible for implementing move semantics, not you.

You want to use std::move to explicitly move something, when it wouldn’t be done normally, like in your test. (Which seems to be fine; was that in Release? You should output the contents of the vector, or the compiler will optimize it away.)

If you want to learn about rvalue references, read this.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)