关于复制构造函数,这个问题是g++自动优化造成的吗?

a_liang_me 2013-07-03 06:36:59
先上代码,然后说问题:
Integer.h
class Integer
{
public :
Integer(int i=0);
~Integer();
Integer(const Integer &);
void setInteger(int i);
int getInteger() const;
private:
int value;

};

Integer.cpp
#include "Integer.h"
#include <iostream>
using namespace std;

Integer::Integer(int i)
:value(i)
{
cout << " in constructor" << endl;
}


Integer::~Integer(void)
{
cout << " in des constructor" << endl;
}

Integer::Integer(const Integer &integer)
{
cout << "in copy mode...." << endl;
}

void Integer::setInteger(int i)
{
value = i;
}

int Integer::getInteger() const
{
return value;
}


main.cpp
#include "Integer.h"
#include <iostream>
using namespace std;

Integer callInteger()
{
//Integer *integer = new Integer(10);
Integer integer(10);
int in = integer.getInteger();
cout << in << endl;
cout << "in func call integer:" << &integer << endl;
return integer;
}

int main()
{
Integer i = callInteger();
cout << "in main:" << &i << endl;
cout << "hello...." << endl;
getchar();
}


在g++下运行,callInteger()得到的Integer对象在函数完成后,没有析构,也没有调用拷贝构造函数创造对象的副本,而是直接将对象赋给了main()中的i。
输出结果:

in constructor
10
in func call integer:0x7fff4309e110
in main:0x7fff4309e110
hello ....
in des constructor

然后把代码在vs2010中运行,在callInteger()中就会对局部变量进行析构,也会调用拷贝构造函数创建副本。
vs2010运行结果:
 in constructor
10
in func call integer:0039F6B8
in copy mode....
in des constructor
in main:0039F7AC
hello....
in des constructor

为什么g++会有如此表现呢?一开始以为是g++自动优化了,可我把 -O0 设置了,还是一样。如果把vs2010设置为release,结果就会与g++有一样的表现。可我明明已经关了g++的自动优化了啊。
...全文
162 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
FrankHB1989 2013-07-04
  • 打赏
  • 举报
回复
又要背书吗…… ISO C++11 12.8/31 When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. ... 显式指定的语义规则就允许省略复制,不是通过1.9的as if等价行为规则调整。编译器可以直接按“优化”了的语义生成这样的代码,不用另外放到优化阶段。
漫步者、 2013-07-03
  • 打赏
  • 举报
回复
RVO,返回值优化呢,与debug/release无关
火头军 2013-07-03
  • 打赏
  • 举报
回复
这个是c++的返回值优化,专有名字是:return value optimization(RVO)不同的编译器厂商对他实现的程度不一样,但是你了解,可以提高编程效率。 c++对象模型 和 more effective c++ 都有讲到
taodm 2013-07-03
  • 打赏
  • 举报
回复
因为这个优化不受debug/relase什么的控制。

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧