C++中的copy-and-swap惯用法是什么?
大家好!我正在学习C++,并试图弄清楚如何正确编写拷贝构造函数和赋值运算符。我读到了三法则,但经常看到有人提到一种叫"copy-and-swap"的惯用法。
我有一个管理动态内存的简单类:
```cpp
class String {
public:
String(const char* str = "") {
size = strlen(str);
data = new char[size + 1];
strcpy(data, str);
}
~String() { delete[] data; }
// 拷贝构造函数
String(const String& other) {
size = other.size;
data = new char[size + 1];
strcpy(data, other.data);
}
// 赋值运算符 - 这里我有问题
String& operator=(const String& other) {
// 如何正确实现?
if (this != &other) {
delete[] data;
size = other.size;
data = new char[size + 1];
strcpy(data, other.data);
}
return *this;
}
private: