如何重载 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);
// ...
}
};
相关文章