#include <utility>
struct S {
explicit S(std::size_t size) : buf_(new char[size]), size_(size) {}
S(S const& other) : S(other.size_) {}
S(S&& other) noexcept { swap(*this, other); }
S& operator=(S const& other) & {
auto t = other;
swap(*this, t);
return *this;
}
S& operator=(S&& other) & noexcept {
swap(*this, other);
return *this;
}
~S() { delete[] buf_; }
friend void swap(S& s1, S& s2) noexcept {
using std::swap;
swap(s1.buf_, s2.buf_); // C.165: not using std::swap
swap(s1.size_, s2.size_); // to using possible ADL
}
private:
char* buf_ = nullptr;
std::size_t size_ = 0U;
};
典型的copy-swap,代码简练。但是Howard Hinnant有不同意见。他的意见是copy-swap每次在copy assignment的时候都生成多余拷贝,性能上不见得可以接受。默认copy assignment operator只应提供basic exception safety,在客户能够接受strong exception guarantee的时候,才每次都生成多余拷贝,即把copy assignment改成
S& operator=(S const& other) & {
if (this != &other) {
if (size_ < other.size_) {
size_ = 0U;
delete[] buf_;
buf_ = new char[other.size_];
size_ = other.size_;
}
std::copy(other.buf_, other.buf_ + other.size_, buf_);
}
return *this;
}
并且提供一个模版函数
template <typename T>
T& strong_assign(T& dest, T src) {
std::swap(dest, src);
return dest;
}
这样,当调用x = y
的时候有最高的效率,如果需要strong exception guarantee,并且能够接受可能的性能损失的话,调用strong_assign(x, y)