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

作者: wheels   2014-07-15 16:28:22
開發平台(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)
請問我對錯誤的理解對嗎?謝謝各位。
作者: chunhsiang (= =)   2014-07-15 17:24:00
這跟變數的生命週期有關係
作者: masan22305 (海豹)   2014-07-16 09:41:00
destruct就記後進先出
作者: Killercat (殺人貓™)   2014-07-16 11:30:00
global一定都是最先ctor最後dtor 這應該沒有疑問吧...

Links booklink

Contact Us: admin [ a t ] ucptt.com