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()


- 将函数的返回值分配给引用 C++? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 如何提取 __VA_ARGS__? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01