#include "c_SmartPtr.h" #include #include // 自訂釋放函數:負責關閉檔案 void close_file_callback(void* ptr, void* args) { FILE* fp = (FILE*)ptr; char* filename = (char*)args; if (fp) { printf("[SmartPtr] 引用計數歸零,自動關閉檔案: %s\n", filename); fclose(fp); } } int main() { printf("--- 1. 建立資源 (Open File) ---\n"); char* my_file = "test.txt"; FILE* fp = fopen(my_file, "w"); if (!fp) return 1; // 寫入一些測試資料 fprintf(fp, "Hello Smart Pointer in C!"); fflush(fp); // 確保資料進硬碟,但先不關閉檔案 // 使用智慧指標接管檔案控制權 c_SmartPtr_t sptr_a = c_SmartPtr_Make(fp, close_file_callback, my_file); printf("sptr_a 建立完成,目前引用計數: %d\n", c_SmartPtr_UseCount(&sptr_a)); // 建立另外兩個空白的智慧指標容器 c_SmartPtr_t sptr_b = {0}; c_SmartPtr_t sptr_c = {0}; printf("\n--- 2. 測試 Copy 語義 (共享檔案控制權) ---\n"); c_SmartPtr_Copy(&sptr_b, &sptr_a); printf("A 的計數: %d, B 的計數: %d\n", c_SmartPtr_UseCount(&sptr_a), c_SmartPtr_UseCount(&sptr_b)); printf("\n--- 3. 測試 Move 語義 (B 所有權轉移給 C) ---\n"); c_SmartPtr_Move(&sptr_c, &sptr_b); printf("Move 後 -> B 計數: %d (已空), C 計數: %d\n", c_SmartPtr_UseCount(&sptr_b), c_SmartPtr_UseCount(&sptr_c)); printf("\n--- 4. 開始依序銷毀指標物件 ---\n"); printf("銷毀 sptr_a...\n"); c_SmartPtr_Destroy(&sptr_a); // 計數 2 -> 1 printf("sptr_a 銷毀後,C 的計數: %d\n", c_SmartPtr_UseCount(&sptr_c)); printf("銷毀 sptr_b (本身已空,無影響)...\n"); c_SmartPtr_Destroy(&sptr_b); printf("銷毀 sptr_c...\n"); // 計數 1 -> 0,自動觸發 close_file_callback 關閉檔案! c_SmartPtr_Destroy(&sptr_c); printf("\n程式結束,所有資源安全回收。\n"); return 0; }