作者su31o4gj83 (哈哈哈哈哈哈哈哈哈哈哈)
看板C_and_CPP
标题[问题] copy constructor 被呼叫的次数
时间Mon Jul 11 09:50:36 2016
开发平台(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://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1468201839.A.724.html
1F:→ su31o4gj83: 错误结果是在我电脑上跑出来的结果 07/11 09:54
2F:→ Caesar08: 因为你的compiler有打开nrvo吧 07/11 11:01
3F:推 serikafan: g++预设是打开的,加上 -fno-elide-constructors 关掉 07/11 12:05
4F:→ serikafan: 正确是两次 copy constructor,原因同你推测的 07/11 12:08
5F:→ su31o4gj83: -fno-elide-constructors 加上就会执行两次, 谢谢你们 07/11 15:54
6F:推 LPH66: 详细关键字就是这个选项或是二楼说的 NRVO 07/11 15:54