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.
}