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

/**
 *  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;
}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值