实现您自己的swap1 函数的一个好处是在 赋值运算符 中管理/传输动态分配的内存,通过使用 复制和交换习语。
如果你有以下课程:
#include <algorithm> // std::copy
#include <cstddef> // std::size_t
class MyArray{
public:
// (default) constructor
MyArray(std::size_t size = 0)
: mSize(size), mArray(mSize ? new int[mSize]() : 0)
{ }
// copy-constructor
MyArray(const MyArray& other)
: mSize(other.mSize), mArray(mSize ? new int[mSize] : 0),
{ std::copy(other.mArray, other.mArray + mSize, mArray); }
// destructor
~MyArray(){ delete [] mArray; }
private:
std::size_t mSize;
int* mArray;
};
1。实现赋值运算符
代替:
MyArray& operator=(const MyArray& other){
if (this != &other){
// get the new data ready before we replace the old
std::size_t newSize = other.mSize;
int* newArray = newSize ? new int[newSize]() : 0;
std::copy(other.mArray, other.mArray + newSize, newArray);
// replace the old data
delete [] mArray;
mSize = newSize;
mArray = newArray;
}
return *this;
}
你可以这样做:
MyArray& operator=(MyArray other){
swap(*this, other);
return *this;
}
2。安全地交换类成员:
friend void swap(MyArray& first, MyArray& second){
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.mSize, second.mSize);
swap(first.mArray, second.mArray);
}
注意:此答案的见解来自this。
1 交换函数是一个非抛出函数,它交换一个类的两个对象,成员对成员。我们可能会想使用std::swap 而不是提供我们自己的,但这是不可能的; std::swap 在其实现中使用复制构造函数和复制赋值运算符,我们最终会尝试根据自身定义赋值运算符!