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

后端 未结 8 2080
粉色の甜心
粉色の甜心 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条回答
  •  野性不改
    2020-11-22 08:58

    Here is a full example, using std::move for a (simple) custom vector

    Expected output:

     c: [10][11]
     copy ctor called
     copy of c: [10][11]
     move ctor called
     moved c: [10][11]
    

    Compile as:

      g++ -std=c++2a -O2 -Wall -pedantic foo.cpp
    

    Code:

    #include 
    #include 
    
    template class MyVector {
    private:
        T *data;
        size_t maxlen;
        size_t currlen;
    public:
        MyVector () : data (nullptr), maxlen(0), currlen(0) { }
        MyVector (int maxlen) : data (new T [maxlen]), maxlen(maxlen), currlen(0) { }
    
        MyVector (const MyVector& o) {
            std::cout << "copy ctor called" << std::endl;
            data = new T [o.maxlen];
            maxlen = o.maxlen;
            currlen = o.currlen;
            std::copy(o.data, o.data + o.maxlen, data);
        }
    
        MyVector (const MyVector&& o) {
            std::cout << "move ctor called" << std::endl;
            data = o.data;
            maxlen = o.maxlen;
            currlen = o.currlen;
        }
    
        void push_back (const T& i) {
            if (currlen >= maxlen) {
                maxlen *= 2;
                auto newdata = new T [maxlen];
                std::copy(data, data + currlen, newdata);
                if (data) {
                    delete[] data;
                }
                data = newdata;
            }
            data[currlen++] = i;
        }
    
        friend std::ostream& operator<<(std::ostream &os, const MyVector& o) {
            auto s = o.data;
            auto e = o.data + o.currlen;;
            while (s < e) {
                os << "[" << *s << "]";
                s++;
            }
            return os;
        }
    };
    
    int main() {
        auto c = new MyVector(1);
        c->push_back(10);
        c->push_back(11);
        std::cout << "c: " << *c << std::endl;
        auto d = *c;
        std::cout << "copy of c: " << d << std::endl;
        auto e = std::move(*c);
        delete c;
        std::cout << "moved c: " << e << std::endl;
    }
    

提交回复
热议问题