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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2021-01-25 4个字节数组转换为IEEE 754浮点数