[問題] copy constructor 被呼叫的次數

看板C_and_CPP作者 (哈哈哈哈哈哈哈哈哈哈哈)時間9年前 (2016/07/11 09:50), 編輯推噓2(204)
留言6則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Apple LLVM version 7.0.2 (clang-700.1.81) Target: x86_64-apple-darwin14.5.0 Thread model: posix 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 我用 g++ -O0 main.cc 編譯後執行 為什麼 main function 在執行 Foo foo1 = Func(); 時 完全沒有 copy constructor 被呼叫 餵入的資料(Input): 預期的正確結果(Expected Output): 一次 copy constructor 被執行 ### ### codepad 上執行的結果是兩次 copy constructor 被執行! ### 這是因為 Func 的回傳值先被複製到一個暫時的變數後 ### 暫時的變數再被複製到 foo1 嗎??? ### 所以總共兩次 copy constructor 被執行 ### 錯誤結果(Wrong Output): in constructor 0x7fff53564b28 ======= 0x7fff53564b28 沒有 copy constructor 被執行 而且 Func 內 local foo 位址與 main 內 foo1 位址相同 程式碼(Code):(請善用置底文網頁, 記得排版) http://codepad.org/81B5HPLf 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 104.59.96.138 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1468201839.A.724.html

07/11 09:54, , 1F
錯誤結果是在我電腦上跑出來的結果
07/11 09:54, 1F

07/11 11:01, , 2F
因為你的compiler有打開nrvo吧
07/11 11:01, 2F

07/11 12:05, , 3F
g++預設是打開的,加上 -fno-elide-constructors 關掉
07/11 12:05, 3F

07/11 12:08, , 4F
正確是兩次 copy constructor,原因同你推測的
07/11 12:08, 4F

07/11 15:54, , 5F
-fno-elide-constructors 加上就會執行兩次, 謝謝你們
07/11 15:54, 5F

07/11 15:54, , 6F
詳細關鍵字就是這個選項或是二樓說的 NRVO
07/11 15:54, 6F
文章代碼(AID): #1NWljlSa (C_and_CPP)