免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2316 | 回复: 7
打印 上一主题 下一主题

[C++] 请教一个构造函数的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-06-14 17:03 |只看该作者 |倒序浏览
  1. #include <iostream>

  2. using namespace std;

  3. class A
  4. {
  5. public:
  6.     A(int)
  7.     {
  8.         cout << "11111" << endl;;
  9.     };
  10.     A(const A&)
  11.     {
  12.         cout << "22222" << endl;;
  13.     };
  14. };


  15. int main()
  16. {
  17.     A a2 = A(47);
  18.     return 0;
  19. }
复制代码
以上代码,我认为应该输出两行“11111”和“22222”,但运行结果只有一行“11111”。1 A(47)调用构造函数生成临时对象输出“11111” 2 这个临时对象初始化a2对象,此时应该输出“22222”。
谁能解释一下原因呢?

论坛徽章:
0
2 [报告]
发表于 2011-06-14 17:21 |只看该作者
you havn't understood what the copy construct function is at all!
see the codes I just modified, which is your expected!
  1. #include <iostream>

  2. using namespace std;

  3. class A
  4. {
  5. public:
  6.    A(int)
  7.    {
  8.      cout << "11111" << endl;;
  9.    };
  10.    A(const A&)
  11.   {
  12.      cout << "22222" << endl;;
  13.   };
  14. };

  15. int main()
  16. {
  17.     A a1(47);
  18.     A a2 = a1;
  19.     return 0;
  20. }
复制代码

论坛徽章:
0
3 [报告]
发表于 2011-06-14 17:23 |只看该作者
去搜一下 RNV,你就明白了

论坛徽章:
0
4 [报告]
发表于 2011-06-14 17:49 |只看该作者

NRV name return value 优化

论坛徽章:
0
5 [报告]
发表于 2011-06-14 18:01 |只看该作者
c++对象模型

论坛徽章:
0
6 [报告]
发表于 2011-06-14 18:04 |只看该作者
because the gcc use the NRVO option to optimaze the codes for improving the performance, but the MS Studio doesn't use the NRVO;

The Visual C++ 8.0 compiler makes use of the flexibility that the standard provides and adds a new feature: Named Return Value Optimization (NRVO). NRVO eliminates the copy constructor and destructor of a stack-based return value. This optimizes out the redundant copy constructor and destructor calls and thus improves overall performance. It is to be noted that this could lead to different behavior between optimized and non-optimized programs (see the Optimization Side Effects section).

论坛徽章:
0
7 [报告]
发表于 2011-06-14 19:27 |只看该作者
以上代码,我认为应该输出两行“11111”和“22222”,但运行结果只有一行“11111”。1 A(47)调用构造函数生 ...
bxb_koala 发表于 2011-06-14 17:03



    这是命名返回值优化,为了消除复制构造函数对性能的影响,在符合条件的情况下,编译器可以将函数的返回值隐式修改为引用,因此A(47)是直接在a2上构造的,无需经过复制构造函数。

论坛徽章:
0
8 [报告]
发表于 2011-06-15 09:45 |只看该作者
本帖最后由 bxb_koala 于 2011-06-15 09:47 编辑
这是命名返回值优化,为了消除复制构造函数对性能的影响,在符合条件的情况下,编译器可以将函数 ...
supermegaboy 发表于 2011-06-14 19:27


It makes sense, Thank you all guys.I found a useful article about NRV written by Stan Lippman.Refer to the below link:
http://blogs.msdn.com/b/slippman/archive/2004/02/03/66739.aspx
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP