Search code examples
c++classshared-ptrswap

Will the specialized shared_ptr::swap() function be used if I use std::swap on a whole class?


Will the std::swap() function work alright against a class which has all sorts of various objects as variable members? Especially, if some of these members are smart pointers?

class test
{
    ...
    std::shared_ptr<other_test>   m_other;
    ...
};

test ta, tb;
std::swap(ta, tb);

The std::swap() compiles, but I have doubts about the functionality. Specifically, I know that smart pointers have a specialized swap (i.e. m_other.swap(rhs.m_other).

I'm using C++14 is that makes a difference.


Solution

  • No, it probably won't. If you don't overload swap for your own class, it will use the move operations of your class in its implementation. These move operations are not going to use swap unless you implemented them yourself.

    If you care about this, implement swap for your class:

    class test {
        // ...
        friend void swap(test& lhs, test& rhs)
        {
            using std::swap;
            // replace a, b, c with your members
            swap(lhs.a, rhs.a);
            swap(lhs.b, rhs.b);
            swap(lhs.c, rhs.c);
        }
        // ...
    };
    

    Note that, until C++20, the proper way to call swap is via ADL:

    using std::swap;
    swap(a, b);
    

    instead of just std::swap(a, b).

    Since C++20, this is no longer the case — std::swap(a, b) automatically uses ADL to select the best overload.