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,这有所作为。

最佳答案

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

如果您对此有所关注,请为您的类(class)实现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选择最佳的重载。

关于c++ - 如果在整个类上使用std::swap,是否将使用专用的shared_ptr::swap()函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57345023/

10-11 22:48
查看更多