展示深拷贝与移动语义的对比

定义 Buffer 类(含深拷贝和移动语义)

```
#include 
#include 
#include 

class Buffer {
public:
    // 默认构造函数(分配内存)
    explicit Buffer(size_t size) : size_(size), data_(new int[size]) {
        std::cout << "构造函数: 分配 " << size_ << " 个元素" << std::endl;
    }

    // 析构函数(释放内存)
    ~Buffer() {
        if (data_) {
            std::cout << "析构函数: 释放 " << size_ << " 个元素" << std::endl;
            delete[] data_;
        }
    }

    // 深拷贝构造函数
    Buffer(const Buffer& other) : size_(other.size_), data_(new int[other.size_]) {
        std::memcpy(data_, other.data_, size_ * sizeof(int));
        std::cout << "深拷贝构造函数" << std::endl;
    }

    // 移动构造函数(右值引用)
    Buffer(Buffer&& other) noexcept : size_(other.size_), data_(other.data_) {
    

你可能感兴趣的:(C++基础,C++)