Why does std::move take a forward reference?

后端 未结 2 521
鱼传尺愫
鱼传尺愫 2020-12-16 02:37

The implementation of std::move basically looks like this:

template
typename std::remove_reference::type&&
mo         


        
2条回答
  •  时光说笑
    2020-12-16 02:47

    Here is some example simplified to the extreme:

    #include 
    #include 
    
    template
    T&& my_move(T& t)
    {
        return static_cast(t);
    }
    
    int main() 
    {
        std::vector v{true};
    
        std::move(v[0]); // std::move on rvalue, OK
        my_move(v[0]);   // my_move on rvalue, OOPS
    }
    

    Cases like the one above may appear in generic code, for example when using containers which have specializations that return proxy objects (rvalues), and you may not know whether the client will be using the specialization or not, so you want unconditional support for move semantics.

提交回复
热议问题