没有swap的常规写法
#include <iostream>
using namespace std;
class Buffer
{
private:
unsigned char *buf;
int capacity;
int length;
public:
explicit Buffer(int capacity) : capacity(capacity), length(0)
{
buf = capacity == 0 ? nullptr : new unsigned char[capacity]{};
cout << "Constructor" << endl;
}
// 拷贝
Buffer(const Buffer &other)
{
length = other.length;
capacity = other.capacity;
buf = new unsigned char[capacity];
copy(other.buf, other.buf + length, buf);
cout << "Copy Constructor" << endl;
}
Buffer &operator=(const Buffer &other)
{
if (this != &other)
{
delete[] buf;
length = other.length;
capacity = other.capacity;
throw buf = new unsigned char[capacity];
copy(other.buf, other.buf + length, buf);
}
cout << "Copy Assignment" << endl;
return *this;
}
// 移动
Buffer(Buffer &&other)
{
length = other.length;
capacity = other.capacity;
buf = other.buf;
other.buf = nullptr;
cout << "Move Constructor" << endl;
}
// 移动赋值运算符函数
Buffer &operator=(Buffer &&other)
{
if (this != &other)
{
delete[] buf;
length = other.length;
capacity = other.capacity;
buf = other.buf;
other.buf = nullptr;
}
cout << "Move Assignment" << endl;
return *this;
}
Buffer &operator=(Buffer &&other)
{
if (this != &other)
{
delete[] buf;
length = other.length;
capacity = other.capacity;
buf = other.buf;
other.buf = nullptr;
}
cout << "Move Assignment" << endl;
return *this;
}
~Buffer() noexcept
{
if (buf)
delete[] buf;
}
};
int main()
{
Buffer A(10);
}
用swap
#include <iostream>
using namespace std;
class Buffer
{
private:
unsigned char *buf;
int capacity;
int length;
public:
explicit Buffer(int capacity) : capacity(capacity), length(0)
{
buf = capacity == 0 ? nullptr : new unsigned char[capacity]{};
cout << "Constructor" << endl;
}
//默认格式friend void swap
friend void swap(Buffer &lhs, Buffer &rhs) noexcept
{
using std::swap;
swap(lhs.buf, rhs.buf);
swap(lhs.capacity, rhs.capacity);
swap(lhs.length, rhs.length);
}
// 拷贝
Buffer(const Buffer &other) : length(other.length),
capacity(other.capacity),
buf(capacity == 0 ? nullptr : new unsigned char[capacity]{})
{
cout << " copy Constructor" << endl;
}
// 拷贝赋值 这里传入的不是引用 左右值都可 不用写移动运算符重载
Buffer &operator=(Buffer other)
{
swap(*this, other);
return *this;
}
// 移动
Buffer(Buffer &&other) noexcept : Buffer(0)
{
cout << "Move Constructor" << endl;
swap(*this, other);
}
// 移动赋值运算符函数
// 用swap可以不用写相当于拷贝赋值
~Buffer() noexcept
{
if (buf)
delete[] buf;
}
};
class BIt
{
public:
Buffer a;
public:
explicit BIt(int size) : a(size) {}
friend void swap(BIt &left, BIt &right)
{
using std::swap;
swap(left.a, left.a);
}
};
int main()
{
Buffer A(10);
int *m = new int[32];
auto a = BIt{100};
BIt{1};
BIt x{100};
swap(a, x);
}