What is std::move(), and when should it be used?

后端 未结 8 2158
粉色の甜心
粉色の甜心 2020-11-22 08:27
  1. What is it?
  2. What does it do?
  3. When should it be used?

Good links are appreciated.

8条回答
  •  猫巷女王i
    2020-11-22 08:56

    "What is it?" and "What does it do?" has been explained above.

    I will give a example of "when it should be used".

    For example, we have a class with lots of resource like big array in it.

    class ResHeavy{ //  ResHeavy means heavy resource
        public:
            ResHeavy(int len=10):_upInt(new int[len]),_len(len){
                cout<<"default ctor"< _upInt; // heavy array resource
            int _len; // length of int array
    };
    

    Test code:

    void test_std_move2(){
        ResHeavy rh; // only one int[]
        // operator rh
    
        // after some operator of rh, it becomes no-use
        // transform it to other object
        ResHeavy rh2 = std::move(rh); // rh becomes invalid
    
        // show rh, rh2 it valid
        if(rh.is_up_valid())
            cout<<"rh valid"<

    output as below:

    default ctor
    move ctor
    rh invalid
    rh2 valid
    copy ctor
    rh3 valid
    

    We can see that std::move with move constructor makes transform resource easily.

    Where else is std::move useful?

    std::move can also be useful when sorting an array of elements. Many sorting algorithms (such as selection sort and bubble sort) work by swapping pairs of elements. Previously, we’ve had to resort to copy-semantics to do the swapping. Now we can use move semantics, which is more efficient.

    It can also be useful if we want to move the contents managed by one smart pointer to another.

    Cited:

    • https://www.learncpp.com/cpp-tutorial/15-4-stdmove/

提交回复
热议问题