2024-03-11 19:04阅读: 8评论: 0推荐: 0

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 中国大陆许可协议进行许可。

posted @   フランドール·スカーレット  阅读(8)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 Scarborough Fair 山田タマル
  2. 2 Faster Than Light Paradox Interactive,Andreas Waldetoft
  3. 3 世界は可愛く出来ている 上海アリス幻樂団
Faster Than Light - Paradox Interactive,Andreas Waldetoft
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作曲 : Andreas Waldetoft

Stars in the sky

Floating in darkness

Soon I will fly

Faster than Light

See through my eyes

Time standing down

Onward to space

Engines Stand By

Sense loss of time

Nebula’s blurring

Lights flashing by

Worlds Unknown

Imminent approach

Sensors reacting

Anon I’m through

Faster Than Light

Suddenly stop

Readings come in

Nothing in sight

Sun glowing bright

Stars in my view

Floating in darkness

Soon I'll go through

Faster than Light