萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ 重載賦值運算子完整指南:深層複製、自我賦值檢查、資源管理三部曲

為什麼需要重載 operator=?

預設賦值運算子執行淺層複製:逐位元複製成員。若類別包含指標成員,會導致兩物件指向同一塊堆記憶體,析構時雙重釋放 (double free) 或記憶體洩漏。

標準重載範式 (C++98 風格)

#include <iostream>
#include <cstring>

class Date {
    int mo, da, yr;
    char *month;                // 動態配置字串
public:
    Date(int m=0, int d=0, int y=0);
    ~Date();
    Date& operator=(const Date& rhs); // 回傳 *this 參考,支援鏈式賦值
    void display() const;
};

// 建構子
Date::Date(int m, int d, int y) : mo(m), da(d), yr(y), month(nullptr) {
    static const char *mos[] = {"January","February","March","April","May","June",
                                "July","August","September","October","November","December"};
    if (m != 0) {
        month = new char[std::strlen(mos[m-1]) + 1];
        std::strcpy(month, mos[m-1]);
    }
}

// 解構子
Date::~Date() {
    delete [] month;
}

// 重載賦值運算子
Date& Date::operator=(const Date& rhs) {
    if (this != &rhs) {               // 1. 自我賦值檢查
        mo = rhs.mo;                    // 2. 複製基本型別成員
        da = rhs.da;
        yr = rhs.yr;
        delete [] month;                // 3. 釋放舊資源
        if (rhs.month) {                // 4. 深層複製指標成員
            month = new char[std::strlen(rhs.month) + 1];
            std::strcpy(month, rhs.month);
        } else {
            month = nullptr;
        }
    }
    return *this;                       // 5. 回傳 *this
}

void Date::display() const {
    if (month) std::cout << month << ' ' << da << ", " << yr << '\n';
}

int main() {
    Date birthday(8, 11, 1979);
    Date newday(12, 29, 2003);
    newday = birthday;                 // 呼叫 operator=
    newday.display();                  // 輸出 August 11, 1979
    return 0;
}

五步驟標準流程

  1. 自我賦值檢查:if (this != &rhs) 避免釋放自己資源。
  2. 複製非資源成員:基本型別、std::string、智慧指標等可直接賦值。
  3. 釋放舊資源:delete/free/close 等。
  4. 深層複製資源:配置新記憶體並複製內容。
  5. 回傳 *this:支援 a = b = c 鏈式賦值。

現代 C++ (C++11+) 最佳實務:Copy-and-Swap 慣用語

class Date {
    // ... 成員相同 ...
    friend void swap(Date& a, Date& b) noexcept {
        using std::swap;
        swap(a.mo, b.mo);
        swap(a.da, b.da);
        swap(a.yr, b.yr);
        swap(a.month, b.month); // 指標交換,無需 new/delete
    }

public:
    Date& operator=(Date rhs) { // 以值傳遞參數 (複製建構子產生副本)
        swap(*this, rhs);         // 交換內容
        return *this;             // rhs 攜帶舊資源離開作用域,析構自動釋放
    }
};
  • 優點:異常安全 (強烈異常保證)、碼簡潔、自動處理自我賦值、利用移動語意 (C++11) 避免不必要複製。
  • 前提:類別需提供 swap 且析構子正確。

Rule of Three / Five / Zero

規則需自訂的特殊成員函式適用場景
Rule of Three (C++98)解構子、複製建構子、賦值運算子管理原始資源 (指標、檔案控制代碼、Socket)
Rule of Five (C++11)+ 移動建構子、移動賦值運算子需高效轉移資源所有權
Rule of Zero (現代最佳)無需自訂任何特殊成員使用 std::string、std::vector、std::unique_ptr 等 RAII 類型封裝資源

結語

重載賦值運算子核心在於深層複製資源、防禦自我賦值、提供強烈異常安全。現代 C++ 強烈建議遵循 Rule of Zero:以標準庫 RAII 容器/智慧指標取代原始指標,讓編譯器自動生成正確的特殊成員函式,徹底杜絕記憶體管理錯誤。

copyright © 萬盛學電腦網 all rights reserved