c++ - 如果我在整个班级上使用 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,这会有所不同。
解决方案
不,它可能不会。如果您不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 来选择最佳重载。
推荐阅读
- visual-studio-2017 - 使用 SQL Server 2017 和 Visual Studio 2017 的常用 python 库
- microsoft-teams - 禁用用户后,他/她在 Microsoft Teams 中的消息会被删除吗?
- c++ - 这些问题都暗示着同样的事情吗?
- javascript - 在 Nodejs 和 Express 中使用 JQuery 需要帮助
- css - 我的 html.erb 视图页面内的内联 css 样式的背景图像仅在开发中显示,但在 heroku 上不显示生产阶段
- react-native - 标题空白和 ImageBackground
- apache-kafka-streams - kafka 流中的聚合和状态存储保留
- php - 使用 php 和 htaccess 创建人造 dyndns
- c# - Unity - 如何制作有弹性的绳索?
- ios - uipagecontrol 当前不动