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

编程入门 行业动态 更新时间:2024-10-10 13:22:02
本文介绍了在类方法实现的主体中使用 std::swap 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

  • using std::swap; 在函数实现的主体内部是什么意思?
  • ADL 是什么意思?
  • what does using std::swap; mean inside the body of a function implementation ?
  • 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.

    更多推荐

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

    本文发布于:2023-11-27 22:43:56,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1639906.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:主体   方法   swap   std

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!