Is this correct usage of C++ 'move' semantics?

后端 未结 4 1490
忘了有多久
忘了有多久 2020-12-07 23:07

Tonight I\'ve been taking a look at some code I\'ve been working on over the last few days, and began reading up on move semantics, specifically std::move. I have a few que

4条回答
  •  被撕碎了的回忆
    2020-12-07 23:31

    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&& doSomething() const
    {
        std::vector 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 doSomething() const
    {
        std::vector 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.

提交回复
热议问题