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

posted @   zwj鹿港小镇  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2021-01-25 4个字节数组转换为IEEE 754浮点数
点击右上角即可分享
微信分享提示