Re: 請問C++ Class中 const static object 的life …

看板Programming作者 (我身在未來)時間17年前 (2008/09/19 02:30), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/4 (看更多)
這種寫法會... compile error 型別不對 所有const static member data會在main function之前完成初始化的動作 在main function結束之前被消滅 但是你是用指標 指向一個匿名的暫時物件 雖然會指標會初始化 指標會消滅 但是它所指向的暫時物件不會被消滅 所以在你的程式結束之前 你要自行想辦法把這個東西delete掉 要不然在某些系統可能造成memory leak. 如下: #include <string> using namespace std; class C { private: const static string* foo; public: static void KillFoo() { delete foo; } }; const string* C::foo = new string("hello"); int main() { //your code //... //when you want to kill foo, maybe in the last line of your code C::KillFoo(); //never use foo hereafter... } ======================================================== 你也可以寫個小程式測試一下到底static member data什麼時候會佔記憶體 什麼時候被消滅... #include <cstdio> class Something { public: Something() { printf("constructor\n"); } ~Something() { printf("destructor\n"); } }; class C { const static Something foo; }; const Something C::foo = Something(); int main() { printf("start\n"); printf("main funciton\n"); printf("end\n"); } ============== constructor start main function end destructor ============== ※ 引述《sorryChen (陳揚和)》之銘言: : 想要在class中定義一個const static object. 就說string : 如果在 : Class C { : const static string* foo; : } : const string foo = new string("hello"); : 請問這個string何時被產生(占記憶體)何時被消滅呢 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.67.8.224
文章代碼(AID): #18qfuurq (Programming)
文章代碼(AID): #18qfuurq (Programming)