Copy and Swap
Copy and Swap
在 c++
中,什么是 copy and swap
?
struct Foo { Foo() { std::cout << "Foo construct\n"; } Foo(const Foo &) { std::cout << "Foo copy construct\n"; } Foo(Foo&&) noexcept { std::cout << "Foo move construct\n"; } auto swap(Foo&) noexcept -> void { } auto operator = ([[maybe_unused]] Foo other) -> Foo& { std::cout << "operator=\n"; this->swap(other); return *this; } }; auto main() -> int { Foo a; Foo b = a; Foo c = std::move(a); }
可以看到,这里的 operator=
传递的是一个值类型,当传递了一个左值时,此时将调用拷贝构造函数,当传递了一个右值时,将调用一个移动构造函数,此时我们就不需要写一坨的 operator=(const T&)
和 operator=(T&&)
了,只需要实现一个 swap
,即可代码的冗余了。
本文作者:フランドール·スカーレット
本文链接:https://www.cnblogs.com/FlandreScarlet/p/18066838
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步