[問題] VC的constructor 呼叫了 destructor?

看板C_and_CPP作者 (Bad_To_The_Bone)時間11年前 (2014/09/22 15:53), 編輯推噓2(2017)
留言19則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 在Programming版問了如何trace code的開始與結束的時候 版上大大提供 宣告一個物件 建構子的時候印出開始符號 解構子的時候印出結束符號 進function就宣告此物件 在BCB測試順利 在VC下 建構子一呼叫完解構子就被呼叫 預期的正確結果(Expected Output): line1 (表示開始) line2 (表示function內容) line3 (表示結束) 錯誤結果(Wrong Output): line1 line3 line2 line3 程式碼(Code):(請善用置底文網頁, 記得排版) .h #include <iostream> using namespace std; struct BEGINEND { public: BEGINEND(char* file, int line, wstring str); ~BEGINEND(void); private: char *file_; int line_; wstring str_; }; ========================================================= .cpp #include "stdafx.h" #include "test.h" #include <iostream> using namespace std; BEGINEND::BEGINEND(char* file, int line, wstring str) { void* ptr; ptr = this; file_ = file; line_ = line; str_ = str; { cout << "line1" << endl; } } BEGINEND::~BEGINEND(void) { void* ptr; ptr = this; cout << "line3" << endl; } int _tmain(int argc, _TCHAR* argv[]) { BEGINEND be = BEGINEND(__FILE__, __LINE__, L"haha"); cout << "line2" << endl; return 0; } 補充說明(Supplement): 錯誤輸出的情況我有試著把this印出 結果 line1 line3 lien2 line3 紅色兩行的this與綠色行的this不同個 想請教一下這情況是哪邊出問題了呢 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.59.147.226 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1411372385.A.CA8.html

09/22 16:02, , 1F
覺得紅色部分是 BEGINEND(__FILE__...) 的生和滅
09/22 16:02, 1F

09/22 16:02, , 2F
然後 be = 是從 copy constructor 建立 be, 所以呼叫到
09/22 16:02, 2F

09/22 16:03, , 3F
沒有 line1 的 constructor, 就沒印 line1 了
09/22 16:03, 3F

09/22 16:03, , 4F
最後面綠色是 be 的毀滅
09/22 16:03, 4F

09/22 16:18, , 5F
要弄這種東西建議用 X a(args...); 這種方式
09/22 16:18, 5F

09/22 17:02, , 6F
不過 VC++ 這行為有一點怪, 你要不要附一下版本? ^^|
09/22 17:02, 6F

09/22 17:09, , 7F
喔喔 感謝AZ大 跟CI大....
09/22 17:09, 7F

09/22 17:09, , 8F
2005的^^;
09/22 17:09, 8F

09/22 17:10, , 9F
改AZ大的宣告可以正常了 不會有紅色的LINE3
09/22 17:10, 9F

09/22 17:14, , 10F
我用 g++ 試類似的寫法, 是會自動變成 azureblaze 講的
09/22 17:14, 10F

09/22 17:14, , 11F
效果.. 而且 optimize 都關了, 用 -O0 也是.. @@"
09/22 17:14, 11F

09/22 17:15, , 12F
g++ 4.8.2
09/22 17:15, 12F

09/22 17:32, , 13F
gcc似乎要-fno-elide-constructors才關得掉
09/22 17:32, 13F

09/22 18:43, , 14F
原來是compiler的行為~
09/22 18:43, 14F

09/22 19:33, , 15F
噢~所以問題解決了? 還沒回你信XD
09/22 19:33, 15F

09/22 19:34, , 16F
感覺應該如二樓所說, 是呼叫 copy constructor
09/22 19:34, 16F

09/22 19:34, , 17F
所以還有臨時物件的建構解構
09/22 19:34, 17F

09/22 19:35, , 18F
吧 (不太熟, 不敢亂說XD)
09/22 19:35, 18F

09/23 11:29, , 19F
感謝大大^^
09/23 11:29, 19F
文章代碼(AID): #1K7zLXoe (C_and_CPP)