免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1762 | 回复: 3

请教关于拷贝构造函数的一个问题 [复制链接]

论坛徽章:
0
发表于 2011-03-06 13:20 |显示全部楼层
大家好,请教一个关于拷贝构造函数的一个问题,代码如下:

  1. #include <iostream>
  2. using namespace std;

  3. class NoCopy
  4. {
  5. public:
  6.         NoCopy(int N)
  7.         {
  8.                 tmp = N;
  9.                 cout << "In Constructor " << tmp << endl;
  10.         }

  11.         NoCopy(const NoCopy& another)
  12.         {
  13.                 tmp = another.tmp;
  14.                 cout << "In Copy-Constructor " << tmp << endl;
  15.         }
  16. private:
  17.         int tmp;
  18. };

  19. int main()
  20. {
  21.         NoCopy a = 12;
  22.         NoCopy b = NoCopy(13);
  23.         return 0;
  24. }
复制代码
其运行结果如下:
In Constructor 12
In Constructor 13


对于代码

  1. NoCopy b = NoCopy(13);
复制代码
我认为应该是调用拷贝构造函数,但是实际运行结果为调用的普通的构造函数。

但是,如果将拷贝构造函数设置为private,则NoCopy b = NoCopy(13)这行代码就会编译错误,原因为访问权限的问题,则证明该行代码其实也与拷贝构造函数有关。但为什么在最终调用的时候却是调用的普通的构造函数呢?

谢谢大家。

论坛徽章:
0
发表于 2011-03-06 16:30 |显示全部楼层
本帖最后由 xyfree 于 2012-01-21 16:28 编辑

论坛徽章:
0
发表于 2011-03-06 17:58 |显示全部楼层
g++

       -fno-elide-constructors
           The C++ standard allows an implementation to omit creating a
           temporary which is only used to initialize another object of the
           same type.  Specifying this option disables that optimization, and
           forces G++ to call the copy constructor in all cases.

这种简单的赋值用的copy构造函数被g++优化掉了

论坛徽章:
0
发表于 2011-03-06 18:48 |显示全部楼层
g++

       -fno-elide-constructors
           The C++ standard allows an implementation to omit  ...
csern 发表于 2011-03-06 17:58



    谢谢,果然是这样的,加上-fno-elide-constructors之后就执行了拷贝构造函数中的语句了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP