C++11 rvalues and move semantics confusion (return statement)

前端 未结 6 1214
死守一世寂寞
死守一世寂寞 2020-11-22 04:29

I\'m trying to understand rvalue references and move semantics of C++11.

What is the difference between these examples, and which of them is going to do no vector cop

6条回答
  •  礼貌的吻别
    2020-11-22 05:07

    None of them will copy, but the second will refer to a destroyed vector. Named rvalue references almost never exist in regular code. You write it just how you would have written a copy in C++03.

    std::vector return_vector()
    {
        std::vector tmp {1,2,3,4,5};
        return tmp;
    }
    
    std::vector rval_ref = return_vector();
    

    Except now, the vector is moved. The user of a class doesn't deal with it's rvalue references in the vast majority of cases.

提交回复
热议问题