什么是复制和交换习语? 在这个问题中,在最重要的答案中,在实现交换公共朋友重载的部分中,实现使用了这个:
friend void swap(dumb_array& first, dumb_array& second){
    //the line of code below
    using std::swap;
    //then it calls the std::swap function on data members of the dumb_array`s
}
Run Code Online (Sandbox Code Playgroud)
我的问题如下:using std::swap这里的用途是什么(答案提到了与启用 ADL 相关的内容);此处特别调用了“使用”的什么用例,添加该行代码的效果和不添加该代码行的效果是什么?
using 语句使此行起作用:
swap(first, second);
Run Code Online (Sandbox Code Playgroud)
请注意,我们可以省略std::前面swap。
重要的是,这std::swap(...)是一个合格的查找,而且swap(...)是一个不合格的查找。主要区别在于,限定查找是在特定名称空间或范围(指定的)中调用函数,而非限定查找更灵活,因为它将查看当前上下文的父范围以及全局名称空间。此外,非限定查找还将查找参数类型的范围。这是一个很好的工具,但也很危险,因为它可以从意想不到的地方调用函数。
ADL 仅适用于非限定查找,因为它必须搜索其他命名空间和范围。
该using std::swap还保证,如果没有功能是通过ADL找到,它会调用std::swap默认。
这个习惯用法允许用户定义交换函数:
struct MyType {
    // Function found only through ADL
    friend void swap(MyType& l, MyType& r) {
        // ...
    }
};
Run Code Online (Sandbox Code Playgroud)