18、拷贝构造、赋值构造、移动构造的简洁代码实现
class Buffer { public: explicit Buffer(int capacity) : capacity_(capacity), len_(0), buff_(new char[capacity] {0}) { std::cout << "默认的构造函数" << std::endl; }; ~Buffer() {}; Buffer(const Buffer& other) noexcept : capacity_(other.capacity_), len_(other.len_), buff_(capacity_ ? new char[capacity_] {0} : nullptr) { if (capacity_) { std::copy(other.buff_, other.buff_ + other.capacity_, this->buff_); } std::cout << "拷贝构造" << std::endl; } Buffer& operator=(Buffer other) noexcept // { std::cout << "赋值拷贝" << std::endl; Swap(*this, other); return *this; } Buffer(Buffer&& other) noexcept: capacity_(0), len_(0), buff_(nullptr) { Swap(*this, other); std::cout << "移动构造" << std::endl; } static void Swap(Buffer& lns, Buffer& rhs) noexcept { std::swap(lns.buff_, rhs.buff_); std::swap(lns.capacity_, rhs.capacity_); std::swap(lns.len_, rhs.len_); } private: int capacity_; int len_; char* buff_; };
参考链接;C++ 右值引用、copy&swap 、std::move 、完美转发、std::forward_哔哩哔哩_bilibili
111