首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C++ String 類手寫實現:深拷貝、運算符重載、三大/五大法則完整演示

     編輯:關於C語言

核心設計要點

  1. 動態內存管理:char* data 指向堆內存,負責釋放
  2. 深拷貝語義:拷貝構造、賦值運算符必須分配新內存並複製內容
  3. 自賦值檢查:if (this == &other) return *this;
  4. 異常安全:先分配新內存,再釋放舊內存,防止分配失敗導致對象損壞
  5. 友元輸出運算符:ostream& operator<<(ostream&, const String&)

完整實現代碼


#include <cstring>
#include <iostream>

class String {
public:
    // 普通構造
    String(const char *str = nullptr) {
        if (str == nullptr) {
            data = new char[1];
            *data = '\0';
        } else {
            size_t len = std::strlen(str);
            data = new char[len + 1];
            std::strcpy(data, str);
        }
    }
    
    // 拷貝構造
    String(const String &other) {
        size_t len = std::strlen(other.data);
        data = new char[len + 1];
        std::strcpy(data, other.data);
    }
    
    // 移動構造 (C++11)
    String(String && other) noexcept : data(other.data) {
        other.data = nullptr;
    }
    
    // 析構
    ~String() {
        delete[] data;
    }
    
    // 拷貝賦值 (Copy-and-swap 惯用法)
    String& operator=(String other) {  // 參數按值傳遞,自動調用拷貝/移動構造
        std::swap(data, other.data);
        return *this;
    }
    
    // 移動賦值 (C++11)
    String& operator=(String && other) noexcept {
        if (this != &other) {
            delete[] data;
            data = other.data;
            other.data = nullptr;
        }
        return *this;
    }
    
    // 友元輸出
    friend std::ostream& operator<<(std::ostream& os, const String& s) {
        return os << s.data;
    }
    
    // 訪問器
    const char* c_str() const { return data; }
    size_t length() const { return std::strlen(data); }
    
private:
    char *data;
};

int main() {
    String s1("hello");
    String s2 = s1;           // 拷貝構造
    String s3;
    s3 = s1;                  // 拷貝賦值
    String s4 = std::move(s1); // 移動構造
    s3 = std::move(s2);       // 移動賦值
    std::cout << s3 << std::endl;
    return 0;
}

關鍵技術點解析

1. Copy-and-swap 惯用法

String& operator=(String other) 參數按值傳遞,編譯器自動選擇拷貝或移動構造。函數體內 swap 交換資源,舊資源隨 other 析構釋放。優勢:

  • 自動處理自賦值
  • 強異常安全(構造失敗則原對象不變)
  • 代碼復用拷貝/移動構造,無重複邏輯

2. 移動語義 (C++11)

轉移所有權而非複製,noexcept 保證不拋出異常,使 STL 容器重新分配時優先使用移動操作,大幅提升性能。

3. 規則三/五/零

  • 規則三:析構、拷貝構造、拷貝賦值(C++98)
  • 規則五:+ 移動構造、移動賦值(C++11)
  • 規則零:優先用 std::string/std::vector/std::unique_ptr 等 RAII 類型,避免手寫資源管理

常見坑點

  • 淺拷貝導致雙重釋放
  • 賦值運算符忘記釋放舊內存(內存洩漏)
  • 賦值運算符異常時對象處於無效狀態
  • 忘記 const 正確性(如 c_str() 應為 const 方法)
  • 輸出運算符非友元無法訪問私有成員

手寫 String 是理解 C++ 資源管理、拷貝控制、移動語義、異常安全的最佳練習。實際項目中請直接使用 std::string。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved