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 ,即可代码的冗余了。

posted @ 2024-03-11 19:04  フランドール·スカーレット  阅读(23)  评论(0)    收藏  举报