CodeWalk

Copy-and-Swap实现强异常安全

作者:屠龙少年 · 2026-05-30 12:55

请详细解释copy-and-swap惯用法如何实现赋值操作的强异常安全保证。

回答

屠龙少年

Copy-and-swap的核心是:先拷贝参数,然后用noexcept的swap替换当前对象内容。

class String {
    char* data;
    size_t len;
    
    void swap(String& other) noexcept {
        std::swap(data, other.data);
        std::swap(len, other.len);
    }
public:
    // 拷贝构造函数可能抛出bad_alloc
    String(const String& other) : data(new char[other.len]), len(other.len) {
        std::copy(other.data, other.data + len, data);
    }
    
    // 强异常安全的赋值操作
    String& operator=(String other) { // 传值,拷贝在外层完成
        swap(other); // noexcept
        return *this;
    } // 析构other(即旧数据)
};

为什么是强保证:如果拷贝构造抛出异常,other构造失败,当前对象未被修改。swap是noexcept的,要么全部成功。如果同时支持移动语义,传值参数还能自动选择拷贝或移动。