DEV Community

Discussion on: The copy and swap idiom

Collapse
 
pauljlucas profile image
Paul J. Lucas

Isn't the pattern that you implement a member swap() function (just like all the STL containers have) and then implement a global non-member swap() in terms of the first swap? Since it's a common pattern, you can also use a custom macro like:

#define EXPOSE_GLOBAL_SWAP(T) \
    friend inline void swap(T &a, T &b) noexcept { a.swap(b); } \
    typedef int fake_type_to_eat_semicolon_after_swap
Enter fullscreen mode Exit fullscreen mode

Then:

class Foo {
public:
    // ...
    void swap(Foo &other);
    EXPOSE_GLOBAL_SWAP(Foo);
};
Enter fullscreen mode Exit fullscreen mode