How to overload std::swap()

后端 未结 4 1950
迷失自我
迷失自我 2020-11-22 15:00

std::swap() is used by many std containers (such as std::list and std::vector) during sorting and even assignment.

But the std

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 15:35

    The right way to overload swap is to write it in the same namespace as what you're swapping, so that it can be found via argument-dependent lookup (ADL). One particularly easy thing to do is:

    class X
    {
        // ...
        friend void swap(X& a, X& b)
        {
            using std::swap; // bring in swap for built-in types
    
            swap(a.base1, b.base1);
            swap(a.base2, b.base2);
            // ...
            swap(a.member1, b.member1);
            swap(a.member2, b.member2);
            // ...
        }
    };
    

提交回复
热议问题