拷贝构造函数和移动构造函数解析

来源:互联网 发布:断开数据库所有连接 编辑:程序博客网 时间:2024/06/06 03:23
/** *  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::coutclass 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;}

原创粉丝点击