为什么std :: swap不使用swap idiom?

NoS*_*tAl 8 c++ template-function argument-dependent-lookup customization-point

正确使用std :: swap是:

using std::swap;
swap(a,b);
Run Code Online (Sandbox Code Playgroud)

它有点冗长,但它确保如果a,b有更好的交换定义它将被选中.

所以现在我的问题是为什么std::swap没有使用这种技术实现,所以用户代码只需要调用std::swap

所以这样的事情(noexcept为了简洁而忽略和约束):

namespace std {
    namespace internal {
        template <class T>      // normal swap implementation
        void swap(T& a, T& b) { // not intended to be called directly
            T tmp = std::move(a);
            a = std::move(b);
            b = std::move(tmp);
        }
    }

    template <class T>
    void swap(T& a, T& b) {
        using internal::swap;
        swap(a,b);
    }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*las 6

这进入了重言式领域,但它没有这样做,因为这不是它的目的.

目的std::swap是成为最后的交换功能.它应该是你直接调用的东西,除非你真正想要的是使用最后的交换.

现在,你可以说你所建议的是一个更好的定制点范例.后见之明总是20/20; 不是STL所做的一切都是正确的想法(见vector<bool>).

至于为什么我们现在不能改变它,那是另一回事.std::swap是最后的交换功能.因此理论上人们可能会调用它并期望它绕过任何用户定义的交换代码.因此,以这种方式改变它会破坏他们的代码.