std::swap() 用于对象安全吗?

Is std::swap() safe to use for objects?

在这个关于复制和交换的question中,接受的答案中有一个 swap() 函数。

friend void swap(dumb_array& first, dumb_array& second) // nothrow
 {
    // enable ADL (not necessary in our case, but good practice)
    using std::swap; 

    // by swapping the members of two classes,
    // the two classes are effectively swapped
    swap(first.mSize, second.mSize); 
    swap(first.mArray, second.mArray);
}

为什么不 std::swap(first, second)

std::swap 依赖赋值运算符。因此,如果赋值运算符要调用 std::swap,这将导致在赋值运算符和 std::swap.

之间来回调用的无限链

关于你标题中的问题。是的,对于具有值语义的 well-behaved class,在 class 的 objects 上调用 std::swap 是安全的。由于上述原因,只有 class 的实现者不能将它用于 copy-and-swap 成语。

代码片段建议用于 C++98,在同一答案中还有另一个建议用于 C++11(移动语义)。

Scott Meyers 的 Effective C++ 一书中很好地解释了 C++98 解决方案具有 swap() 函数的原因。

简述;

  template<typename T>          // typical implementation of std::swap;
  void swap(T& a, T& b)         // swaps a's and b's values
  {
    T temp(a);
    a = b;
    b = temp;
  }

As long as your types support copying (via copy constructor and copy assignment operator), the default swap implementation will let objects of your types be swapped without your having to do any special work to support it.

However, the default swap implementation may not thrill you. It involves copying three objects: a to temp, b to a, and temp to b. For some types, none of these copies are really necessary. For such types, the default swap puts you on the fast track to the slow lane.

Foremost among such types are those consisting primarily of a pointer to another type that contains the real data. A common manifestation of this design approach is the "pimpl idiom"...