1. 程式人生 > >c++11 移動拷貝、移動賦值簡單Demo

c++11 移動拷貝、移動賦值簡單Demo

#include <iostream>
using namespace std;
class A {
public:
    A() : p_(new int(3)){
        cout << "constructor numbers = : " << ++count1_ << endl;
    }

    A(const A& lh) : p_(new int(*lh.p_)) {
        cout << "copy constructor numbers = : " << ++count2_ << endl;
    }

    A(A && a) {
        p_ = a.p_;
        a.p_ = nullptr;
        cout << "move copy" << endl;
    }

    A& operator=(const A& lh) {
        if (this != &lh) {
            p_ = new int(*lh.p_);
        }
        cout << "assignment" << endl;
        return *this;
    }

    A& operator=(A && a) {
        if (this != &a) {
            p_ = a.p_;
            a.p_ = nullptr;
        }
        cout << "move assignment" << endl;
        return *this;
    }

    ~A() {
        delete p_;
        cout << "desconstructor numbers = : " << ++count3_ << endl;
    }

    int get_value() const {
        return *p_;
    }
    
private:
    static int count1_;
    static int count2_;
    static int count3_;
    int *p_ = { nullptr };
};

int A::count1_ = 0;
int A::count2_ = 0;
int A::count3_ = 0;

A GetA(bool flag) {
    A a;
    A b;
    if (flag) {
        return a;
    } else
        return b;
}

int main()
{
    {
        A a = GetA(false);
        cout << "a = " << a.get_value() << endl;
        A b;
        b = std::move(a);
        cout << "b = " <<b.get_value() << endl;
    }
    return 0;
}