[問題] c++ 實際建立與釋放object的時機點

看板C_and_CPP (C/C++)作者時間11年前 (2014/07/15 16:28), 11年前編輯推噓1(102)
留言3則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux 預期的結果(Expected Output): 1. ObjA 1. ObjC 1. ObjB 1. ObjD 1. ObjE 1. ObjF 2. ObjD 2. ObjF 2. ObjC 2. ObjA 程式跑出的結果(Wrong Output): 1. ObjA 1. ObjB 1. ObjC 1. ObjD 1. ObjE 1. ObjF 2. ObjD 2. ObjC 2. ObjF 2. ObjA 程式碼(Code):(請善用置底文網頁, 記得排版) #inlcude <iostream> #inlcude <string> using namespace std; class OB{ public: string name; OB(string name){ this->name = name; cout << "1. " << this->name << endl; } ~OB(){ cout << "2. " << this->name << endl; } }; void func(){ OB ObjD("ObjD"); OB* pObjE = new OB("ObjE"); static OB ObjF("ObjF"); } OB ObjA("ObjA"); int main(){ OB* pOB = new OB("ObjB"); OB ObjB("ObjC"); func(); retunr 0; } 補充說明(Supplement): 昨天去桃園某外台商公司面試的題目, new沒有delete會有memory leak我知道, 但目前我好像有兩個地方是錯的,分別是: 1. 原來靜態宣告完object還沒construct, 要等到跑到該行時才會真正建立。 2. destruct的時候會先跑local才跑global(包含static) 請問我對錯誤的理解對嗎?謝謝各位。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.28.212 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1405412905.A.935.html ※ 編輯: wheels (140.112.28.212), 07/15/2014 16:29:17

07/15 17:24, , 1F
這跟變數的生命週期有關係
07/15 17:24, 1F

07/16 09:41, , 2F
destruct就記後進先出
07/16 09:41, 2F

07/16 11:30, , 3F
global一定都是最先ctor最後dtor 這應該沒有疑問吧...
07/16 11:30, 3F
文章代碼(AID): #1JnEOfar (C_and_CPP)
文章代碼(AID): #1JnEOfar (C_and_CPP)