什么是 C++ 中的 Copy-and-Swap 惯用法以及何时使用它?
大家好!我开始学习 C++,并试图弄清楚如何正确重写赋值运算符。我知道需要注意自赋值和释放旧资源,但我的代码看起来很糟糕,而且我经常出错。
以下是我的动态数组类示例:
```cpp
class MyArray {
int* data;
size_t size;
public:
MyArray(size_t s) : size(s), data(new int[s]) {}
~MyArray() { delete[] data; }
// 有问题的赋值运算符
MyArray& operator=(const MyArray& other) {
if (this != &other) { // 检查自赋值
delete[] data; // 释放旧数据
size = other.size;
data = new int[size]; // 分配新内存
std::copy(other.data, other.data + size, data);
}
return *this;
}
// 拷贝构造函数也存在
MyArray(const MyArray& other) : size(other.size), data(new int[other.