编译器优化问题

danny1221 2008-03-13 10:48:41
#include <cstdio>

class B {
public:
B( ) { print_this(); printf( "default constructor\n" ); }
~B( ) { print_this(); printf( "destructor\n" ); }
B( int i ) : data( i ) {
print_this(); printf("constructed by parameter%d\n", data );
}
B( const B& b ) { data = b.data; print_this(); printf( "copy constructor\n" ); }
B& operator= ( const B& b ) {
if( this != &b ) {
data = b.data;
print_this();
printf( "copy assignment\n" );
}
return *this;
}
void print_this( ) {
printf( "0x%08x\n", this );
}
private:
int data;
};

B Play( B b )
{
b.print_this( );
return b;
}

int main( )
{
B tmp = Play(5);
}
对输出结果不太明白,编译器是怎么优化的?
...全文
115 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
danny1221 2008-03-14
  • 打赏
  • 举报
回复
我开始以为Play(5)产生的临时对象传递f(B b)时,Play(5)会copy给b,然后析构Play(5).然后f的返回值会调用operator= 赋值给tmp.
看来编译直接把这两步都优化了,是吧?
mathe 2008-03-14
  • 打赏
  • 举报
回复
编译器的优化不会改变输出结果,不然就是错误的优化了。
redleaves 2008-03-14
  • 打赏
  • 举报
回复
如果你没有少拷贝结果,那就是你的编译器有问题。少销毁了一个对象。
B tmp = Play(5);
1.这一句里Play(5),由于它的参数,会构造一个临时对象,于是,产生了
0x0022ff40
constructed by parameter5
2.之后,在Play里调用print_this,输出了0x0022ff40
3.由于C++标准允许返回值优化,所以Play的返回值不会重新构造一个新对象。
之后就是tmp =的操作,等价于拷贝构造,这时输出了
0x0022ff50
copy constructor
4.在这个表达式结束以后,产生的临时对象生命周期结束,析构对象,输出了
0x0022ff40
destructor
5.main函数结束,这时应该析构tmp,应该输出
0x0022ff50
destructor

你结的结果少了第5步?
而且对于3中说的优化,有的编译器也许没有实现,所以有可能会多产生一个对象。
redleaves 2008-03-14
  • 打赏
  • 举报
回复
to mathe:
这倒不尽然,上面的返回值优化,按你的说法就是错误的优化。因为它会导致少构造一个临时对象。可是在语意上,是没有什么问题的。

to 楼主:
你应该再看一下C++的书关于对象构造的内容。
A a = 1; <=> A a = A(1); <=> A a(A(1));
a = 1; <=> a = A(1); <=> a.operator=(A(1));
定义对象的时候的'='不是赋值,是拷贝构造。

过去的我 2008-03-13
  • 打赏
  • 举报
回复
0x0022ff40
constructed by parameter5
0x0022ff40
0x0022ff50
copy constructor
0x0022ff40
destructor

试了几次不同的debug和release版本,输出都是上面的结果啊,啥优化?
过去的我 2008-03-13
  • 打赏
  • 举报
回复
具体要看汇编码啊

64,637

社区成员

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

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