我试图学习和采用复制交换习语,遵循对这个问题的全面解释:the Copy-Swap Idiom .
但我发现了一些我从未见过的代码:using std::swap;//在这个例子中允许 ADL
class dumb_array
{
public:
// ...
void swap(dumb_array& pOther) // nothrow
{
using std::swap; // allow ADL /* <===== THE LINE I DONT UNDERSTAND */
swap(mSize, pOther.mSize); // with the internal members swapped,
swap(mArray, pOther.mArray); // *this and pOther are effectively swapped
}
};
using std::swap;
在函数实现的主体中是什么意思?- ADL 是什么意思?
最佳答案
这种机制通常用于模板代码,即 template <typename Value> class Foo
.
现在的问题是使用哪个交换。 std::swap<Value>
会起作用,但可能并不理想。很有可能swap
的过载更好。用于类型 Value
,但那会在哪个命名空间中?几乎可以肯定它不在 std::
中(因为这是非法的),但很可能在 Value
的命名空间中.有可能,但还不确定。
在这种情况下,swap(myValue, anotherValue)
将为您提供可能的“最佳”交换。 Argument Dependent Lookup 将在 Value
的命名空间中找到任何交换。来自。否则 using
指令启动,std::swap<Value>
将被实例化并使用。
在您的代码中,mSize
可能是整数类型,并且 mArray
一个指针。两者都没有关联的命名空间,std::swap
无论如何,99.9% 的确定性对他们来说是最佳的。因此,using std::swap;
声明在这里似乎没用。
关于c++ - 类方法实现主体内的 `using std::swap` 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4782692/