看板 C_and_CPP 關於我們 聯絡資訊
開發平台(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
su31o4gj83: 錯誤結果是在我電腦上跑出來的結果 07/11 09:54
Caesar08: 因為你的compiler有打開nrvo吧 07/11 11:01
serikafan: g++預設是打開的,加上 -fno-elide-constructors 關掉 07/11 12:05
serikafan: 正確是兩次 copy constructor,原因同你推測的 07/11 12:08
su31o4gj83: -fno-elide-constructors 加上就會執行兩次, 謝謝你們 07/11 15:54
LPH66: 詳細關鍵字就是這個選項或是二樓說的 NRVO 07/11 15:54