C++备忘录104:copy-swap idiom or not?

#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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值