類 `cipher::encrypt()` 每次調用 `new char[]` 分配緩衝區並返回,析構時需**一次性釋放所有歷史分配**。
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
};
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;
}
};