#include <iostream>
#include <algorithm>
class Buffer {
private:
int* data_;
size_t size_;
public:
// 构造函数
Buffer(size_t size = 0) : size_(size) {
data_ = (size > 0) ? new int[size] : nullptr;
std::cout << "构造 Buffer,大小: " << size_ << std::endl;
}
// 析构函数
~Buffer() {
delete[] data_;
std::cout << "析构 Buffer,大小: " << size_ << std::endl;
}
// 拷贝赋值
Buffer& operator=(const Buffer& other) {
std::cout << "拷贝赋值" << std::endl;
if (this != &other) {
delete[] data_;
size_ = other.size_;
data_ = (size_ > 0) ? new int[size_] : nullptr;
std::copy(other.data_, other.data_ + size_, data_);
}
return *this;
}
// 移动赋值
Buffer& operator=(Buffer && other) noexcept {
std::cout << "移动赋值" << std::endl;
if (this != &other) {
delete[] data_; // 释放当前资源
// 窃取资源
data_ = other.data_;
size_ = other.size_;
// 置空源对象
other.data_ = nullptr;
other.size_ = 0;
}
return *this;
}
// 获取大小
size_t size() const { return size_; }
// 获取数据指针
int* data() const { return data_; }
};
int main() {
Buffer buf1(100); // 构造 buf1
Buffer buf2; // 构造空 buf2
std::cout << "--- 拷贝赋值 ---" << std::endl;
buf2 = buf1; // 拷贝赋值
std::cout << "buf1 大小: " << buf1.size() << std::endl;
std::cout << "buf2 大小: " << buf2.size() << std::endl;
std::cout << "--- 移动赋值 ---" << std::endl;
Buffer buf3;
buf3 = std::move(buf1); // 移动赋值
std::cout << "buf1 大小: " << buf1.size() << std::endl; // 0
std::cout << "buf3 大小: " << buf3.size() << std::endl; // 100
return 0;
}