1. 程式人生 > >拷貝建構函式和移動建構函式解析

拷貝建構函式和移動建構函式解析

/**
 *  by: gongzhihui
 *      2017.12.5
 * 
 *  拷貝建構函式呼叫時機: 
 *      1. 物件作為函式引數
 *      2. 物件作為函式返回值
 *      3. 用一個物件初始化另一個物件: 
 *          T t1;
 *          T t2(ti);
 *          T t3 = t1;  此處的 = 不是賦值運算子
 *  
 *  拷貝賦值運算子:
 *      T t1;
 *      T t2;
 *      t1 = t2; 
 *      除了 類名 物件 = 物件 外的 =  應該都是賦值運算子
 *  
 *  移動建構函式:
 *      用右值初始化物件。
 *      std::move(物件)將物件轉為右值
 *  
 *  移動賦值運算子
 *      T t1;
 *      t1 = std::move(T());
 */


#include <iostream>       // std::cout

class A
{
public:
    int a;

    //一個引數的建構函式(也叫做轉換建構函式)
    A(int i):a(i)
    {
        printf("construct is called! %d \n",i);
    }

    ~A()
    {
        printf("deconstruct is called! \n");
    }

    //拷貝建構函式
    A(const A &v)
    {
        this->a = v.a;
        printf("copy construct is called %d\n", a);
    }
    
    //拷貝賦值運算子
    A& operator = (const A &v)
    {
        printf("= is called \n");
        if(this == &v)
            return *this;
        a = v.a;
        return *this;
    }

    //移動建構函式
    A(A &&v)
    {
        this->a = v.a;
        printf("move construct is called %d\n", a);
    }

    //移動賦值運算子
    A& operator = (A &&v)
    {
        printf("move = is called \n");
        if(this == &v)
            return *this;
        a = v.a;
        return *this;
    }
};

int main ()
{
    A a(1);    //呼叫建構函式
    A b(a);    //呼叫拷貝建構函式
    A c = a;   //呼叫拷貝建構函式
    
    A d(2);
    d = a;     //呼叫拷貝賦值運算子
    
    A e = std::move(A(3)); //呼叫移動建構函式
    A f(4);
    f = std::move(A(5));   //呼叫移動賦值運算子
    return 0;
}