Search code examples
c++assignment-operatormixinscrtpcopy-and-swap

reusing the copy-and-swap idiom


I'm trying to put the copy-and-swap idiom into a reusable mixin:

template<typename Derived>
struct copy_and_swap
{
    Derived& operator=(Derived copy)
    {
        Derived* derived = static_cast<Derived*>(this);
        derived->swap(copy);
        return *derived;
    }
};

I intend it to be mixed in via CRTP:

struct Foo : copy_and_swap<Foo>
{
    Foo()
    {
        std::cout << "default\n";
    }

    Foo(const Foo& other)
    {
        std::cout << "copy\n";
    }

    void swap(Foo& other)
    {
        std::cout << "swap\n";
    }
};

However, a simple test shows that it is not working:

Foo x;
Foo y;
x = y;

This only prints "default" twice, neither "copy" nor "swap" is printed. What am I missing here?


Solution

  • I am afraid this is one area where a macro is necessary, because of the complex rules about automatically generated copy and assignment operators.

    No matter what you do, you are in either of two cases:

    • You have provided (explicitly) a declaration of the assignment operator, in which case you are expected to provide a definition too
    • You have not provided (explicitly) a declaration of the assignment operator, in which case the compiler will generate one if the base classes and non-static members have one available.

    The next question, therefore, is: Is it worth it to automate such writing ?

    Copy-And-Swap is only used for very specific classes. I do not think it's worth it.