在类方法实现的主体中使用 std::swap 是什么意思?

2022-01-07 00:00:00 using c++ stl std argument-dependent-lookup

按照对这个问题的详尽解释,我试图学习和采用复制交换习语:复制交换习语.

I was trying to learn and adopt the copy-swap idiom following this thorough explanation on this question: the Copy-Swap Idiom.

但我发现了一些我从未见过的代码:using std::swap;//在这个例子中允许 ADL

But I found some code I had never seen: using std::swap; // allow ADL in this example

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
    }
};

  1. using std::swap; 在函数实现的主体内部是什么意思?
  2. ADL 是什么意思?
  1. what does using std::swap; mean inside the body of a function implementation ?
  2. what does ADL mean ?

推荐答案

这种机制通常用于模板化代码中,即 template Foo类.

This mechanism is normally used in templated code, i.e. template <typename Value> class Foo.

现在的问题是使用哪个交换.std::swap 会起作用,但它可能并不理想.很有可能对于 Value 类型有更好的 swap 重载,但是在哪个命名空间中呢?它几乎可以肯定不在 std:: 中(因为这是非法的),而很有可能在 Value 的命名空间中.有可能,但远不能确定.

Now the question is which swap to use. std::swap<Value> will work, but it might not be ideal. There's a good chance that there's a better overload of swap for type Value, but in which namespace would that be? It's almost certainly not in std:: (since that's illegal), but quite likely in the namespace of Value. Likely, but far from certain.

在这种情况下,swap(myValue, anotherValue) 将为您提供可能的最佳"交换.Argument Dependent Lookup 将在 Value 来自的命名空间中找到任何交换.否则 using 指令会启动,并且 std::swap 将被实例化和使用.

In that case, swap(myValue, anotherValue) will get you the "best" swap possible. Argument Dependent Lookup will find any swap in the namespace where Value came from. Otherwise the using directive kicks in, and std::swap<Value> will be instantiated and used.

在您的代码中,mSize 可能是一个整数类型,而 mArray 是一个指针.两者都没有关联的命名空间,而且 std::swap 无论如何都具有 99.9% 的确定性.因此,using std::swap; 声明在这里似乎没有用.

In your code, mSize is likely an integral type, and mArray a pointer. Neither has an associated namespace, and std::swap is with 99.9% certainty optimal for them anyway. Therefore, the using std::swap; declaration seems useless here.

相关文章