How to overload std::swap()(如何重载 std::swap())
问题描述
std::swap()
被许多 std 容器(例如 std::list
和 std::vector
)使用排序甚至分配.
std::swap()
is used by many std containers (such as std::list
and std::vector
) during sorting and even assignment.
但是 swap()
的 std 实现非常通用,对于自定义类型来说效率很低.
But the std implementation of swap()
is very generalized and rather inefficient for custom types.
因此可以通过使用自定义类型特定实现重载 std::swap()
来提高效率.但是如何实现它才能被 std 容器使用?
Thus efficiency can be gained by overloading std::swap()
with a custom type specific implementation. But how can you implement it so it will be used by the std containers?
推荐答案
重载 std::swap
的实现(也就是专门化它)的正确方法是将它写在同一个命名空间中作为您要交换的内容,以便可以通过 参数相关查找 (ADL) 找到它).一件特别容易的事情是:
The right way to overload std::swap
's implemention (aka specializing it), 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);
// ...
}
};
这篇关于如何重载 std::swap()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何重载 std::swap()


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30