在Effective c++第三版的第25条建议中,Scott Meyers建议在与类相同的命名空间中实现swap函数,然后在交换时使用using std :: swap,并且作者在此处说:
为什么
作者建议始终以这种方式交换对象:For example, if you were to write the call to swap this way:
std::swap(obj1,obj2); // the wrong way to call swap
you'd force the compiler to consider only the swap in std, thus eliminating the possibility of getting a more appropriate T-specific version defined elsewhere. Alas, some misguided programmers do qualify calls to swap in this way, and that is why it's important to totally specialize std::swap for your classes.
#include <iostream>
#include <utility>
#define CUSTOM_SWAP
namespace aaa{
struct A
{
};
#ifdef CUSTOM_SWAP
void swap( A&, A& )
{
std::cout<<"not std::swap"<<std::endl;
}
#endif
}
int main()
{
using std::swap; // add std::swap to a list of possible resolutions
aaa::A a1;
aaa::A a2;
swap(a1,a2);
}
为什么
std::swap
不在全局命名空间中?这样,就可以更简单地添加自定义的交换功能。
swap
,并期望在传递其他类型时无法编译。如果在全局范围内使用swap
模板,则仍会编译。 - jrokstd::swap(x,y);
”,那么我敢说这是一个错误的教训。如果你知道你想调用std::swap
,那么请明确地调用它。 - jrok