构造函数可以有多个重载,而拷贝构造函数、拷贝赋值函数只能有一个重载。
什么是 big five ?
构造函数、拷贝构造函数、拷贝赋值函数、移动构造函数、移动赋值函数
.
对于一个类而言,什么情况下使用big five ? 什么情况下使用默认的就可以了呢?
一个类里面只要它带着指针的成员(point number),一般就需要自己去写出 big five .
如果这个类不带point number,一般用默认的就可以了。
以下面例子为例:
class Foo {
public:
Foo(int i) : _i(i) {}
Foo() = default; // ok 构造函数可以重载
Foo(const Foo& x) : _i(x._i) {}
// Foo(const Foo&) = default; // error, `Foo::Foo(cosnt Foo&)` cannot be overload
// Foo(cosnt Foo&) = delete; // error, `Foo::Foo(cosnt Foo&)` cannot be overload
Foo& operator = (const Foo& x)
{
this->_i = x._i;
return *this;
}
// Foo& operator = (const Foo& x) = default; // error, `Foo& Foo::operator = (const Foo& x)` cannot be overload
// Foo& operator = (const Foo& x) = delete; // error, `Foo& Foo::operator = (const Foo& x)` cannot be overload
// void func1() = default; // error, `void Foo::func1()` cannot be defaulted
// =default 用于 big-five 之外毫无意义,会报错
void func2() = delete; // ok, =delete 可以用于任何函数身上。(=0 只能用于 virtual 函数)
// ~Foo() = delete; // 这会造成使用 Foo object 时出错。 use of deleted function `Foo::~Foo()`
~Foo() = default;
private:
int _i;
};
Foo f1(5);
Foo f2; // 如果没有写 =default 版本, 会报 no matching function for call to `Foo::Foo()`
Foo f3(f1); // 如果 copy ctor = delete; 会报 error, use of deleted function `Foo::Foo(const Foo&)`
f3 = f2; // 如果 copy assign = delete; 会报 error, use of deleted function `Foo& Foo::operator = (const Foo&)`