首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 析構函數釋放成員函數多次 new 內存:記錄指針數組或智能指針容器

     編輯:程式設計疑難解答

問題

類 `cipher::encrypt()` 每次調用 `new char[]` 分配緩衝區並返回,析構時需**一次性釋放所有歷史分配**。

方案一:成員 `std::vector>` 自動管理(推薦 C++11+)

class cipher {
    std::vector> buffers; // 自動釋放
    char key[128];
public:
    cipher(const char* key_) { strcpy(key, key_); }
    char* encrypt(const char* text) {
        int len = (strlen(text)/128 + 1) * 128;
        auto buf = std::make_unique(len);
        strcpy(buf.get(), text);
        strcat(buf.get(), key);
        char* raw = buf.get(); // 返回裸指針供調用者用完即棄
        buffers.push_back(std::move(buf)); // 轉移所有權給容器
        return raw;
    }
    // 析構函數無需寫代碼,vector 自動釋放所有 unique_ptr
};

方案二:手動指針數組(C++98 風格,教學用)

class cipher {
    char** allocated; // 動態指針數組
    int count;
    char key[128];
public:
    cipher(const char* key_) : allocated(nullptr), count(0) { strcpy(key, key_); }
    char* encrypt(const char* text) {
        int len = (strlen(text)/128 + 1) * 128;
        char* buf = new char[len];
        strcpy(buf, text);
        strcat(buf, key);
        // 擴容指針數組
        char** tmp = new char*[count + 1];
        for (int i = 0; i < count; ++i) tmp[i] = allocated[i];
        tmp[count] = buf;
        delete[] allocated;
        allocated = tmp;
        ++count;
        return buf;
    }
    ~cipher() {
        for (int i = 0; i < count; ++i) delete[] allocated[i];
        delete[] allocated;
    }
};

核心點

  • **所有權轉移**:`encrypt` 返回裸指針給調用者**短期使用**,所有權歸類管理,析構時統一釋放。
  • **調用者不可 `delete` 返回指針**,否則雙重釋放。
  • 現代 C++ **首選智能指針容器**,零手動內存管理,異常安全。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved