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
,它将在其实现中使用您的类的移动操作。这些移动操作不会使用 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 来选择最佳重载。
关于c++ - 如果我在整个类上使用 std::swap,是否会使用专门的 shared_ptr::swap() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57345023/