c++ copy constructor, copy assignment, move constructor, move assignment functions

c++编译器生成的默认构造函数

  • C++ 总是会为class/struct默认生成copy constructor, copy assignment,如果用户没有显示定义的话 。值得注意:即使有些时候成员变量需要特殊的移动构造函数才可以正常工作,在用户没有提供的情况下,编译器也会默认生成,并不会保证代码运行的正确性。
  • 对于move constructor, move assignment的默认生成,只有当用户没有定义copy constructor,copy assignment,也没有定义destructor的时候,编译器才会默认生成move constructor, move assignment。另外默认的移动构造函数并不会把other的里面指针设置成nullptr.(这需要你自定义好拷贝构造函数)。如果没有默认生成,但是仍然有接口调用&&的时候,会匹配拷贝构造函数。
  • 如果用户定义了含参数构造函数,那么默认构造函数将不再默认生成

ref: https://www.zhihu.com/question/52138073

// Compiler will generate default copy constructor, copy assignment, move
// constructor, move assignment functions.
struct EasyClass {
  /* data */
  EasyClass(int a) { data.resize(100, a); }

  std::vector<int> data;
};

struct HardClass {
  HardClass(const int& a) { a_ = &a; }
  const int* a_ = nullptr;
};


  {  // EasyClass x;
    EasyClass x(1);
    EasyClass y_copy_constructor(x);
    EasyClass y_copy_assignment = x;
    EasyClass y_move_constructor(std::move(x));
    EasyClass y_move_assignment = std::move(x);
  }
  {
    HardClass x(1);
    HardClass y_copy_constructor(x);
    cout << *y_copy_constructor.a_ << endl;  // normal
    HardClass y_copy_assignment = x;
    cout << *y_copy_assignment.a_ << endl;  // normal
    HardClass y_move_constructor(std::move(x));
    cout << *y_move_constructor.a_ << endl;  // normal
    HardClass y_move_assignment = std::move(x); // 调用编译器生成的默认移动构造函数
    cout << *y_move_assignment.a_ << endl;  // invalid address, maybe coredump.
  }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值