首页 > 解决方案 > 如果我在整个班级上使用 std::swap 会使用专门的 shared_ptr::swap() 函数吗?

问题描述

std::swap() 函数对于具有各种对象作为变量成员的类是否可以正常工作?特别是,如果其中一些成员是智能指针?

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

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

编译,但我对std::swap()功能有疑问。具体来说,我知道智能指针有一个专门的交换(即m_other.swap(rhs.m_other).

我使用的是 C++14,这会有所不同。

标签: c++classshared-ptrswap

解决方案


不,它可能不会。如果您不swap为自己的类重载,它将在其实现中使用您的类的移动操作。swap除非您自己实现它们,否则这些移动操作不会使用。

如果您关心这一点,swap请为您的班级实施:

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);
    }
    // ...
};

请注意,在 C++20 之前,正确的调用方式swap是通过 ADL:

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

而不仅仅是std::swap(a, b).

从 C++20 开始,情况不再如此——std::swap(a, b)自动使用 ADL 来选择最佳重载。


推荐阅读