class MyClass {
public:
// 默认构造函数
MyClass() {
// 初始化成员变量等操作
}
// 拷贝构造函数
MyClass(const MyClass& other) {
// 深拷贝成员变量等操作
}
// 拷贝赋值运算符重载函数
MyClass& operator=(const MyClass& other) {
if (this != &other) {
// 释放当前对象资源
// 深拷贝成员变量等操作
}
return *this;
}
// 移动构造函数
MyClass(MyClass&& other) noexcept {
// 接管 other 的资源
// 将 other 置为可析构的状态
}
// 移动赋值运算符重载函数
MyClass& operator=(MyClass&& other) noexcept {
if (this != &other) {
// 释放当前对象资源
// 接管 other 的资源
// 将 other 置为可析构的状态
}
return *this;
}
};
- 默认构造函数:当创建一个类的对象但没有提供任何初始化参数时会调用,例如
MyClass obj;
。
- 拷贝构造函数:当使用一个已存在的对象来初始化新对象时调用,例如
MyClass obj2(obj1);
或者函数按值传递对象时。
- 拷贝赋值运算符重载函数:当对已存在的对象进行赋值操作时调用,例如
obj1 = obj2;
。
- 移动构造函数:当使用一个临时对象(右值)来初始化新对象时调用,例如
MyClass obj3(std::move(obj2));
。
- 移动赋值运算符重载函数:当将一个临时对象(右值)赋值给已存在的对象时调用,例如
obj1 = std::move(obj2);
。