so true

心怀未来,开创未来!
随笔 - 160, 文章 - 0, 评论 - 40, 引用 - 0
数据加载中……

C++中临时变量的优化与产生!

#include <iostream>
using namespace std;

class A{
public:
 A(){
  cout<<"ctor"<<endl;
 }
 ~A(){
  cout<<"dtor x="<<x<<endl;
 }
 void operator =(A a){
  cout<<a.x<<" wokao"<<endl;
 }
 int x;
};

A func(A a){
 return a;
}

void main(){
 A a1;
 a1=func(A());
}
输出结果:
ctor
ctor
dtor x=-858993460
-858993460 wokao
dtor x=-858993460
dtor x=-858993460
dtor x=-858993460
dtor x=-858993460
Press any key to continue

======================================
为类A添加一个拷贝构造函数后:
#include <iostream>
using namespace std;

class A{
public:
 A(){
  cout<<"ctor"<<endl;
 }
 A(A& a){
  cout<<"copy ctor"<<endl;
 }
 ~A(){
  cout<<"dtor x="<<x<<endl;
 }
 void operator =(A a){
  cout<<a.x<<" wokao"<<endl;
 }
 int x;
};

A func(A a){
 return a;
}

void main(){
 A a1;
 a1=func(A());
}

运行结果:
ctor
ctor
copy ctor
dtor x=4856604
4856604 wokao
dtor x=4856604
dtor x=-858993460
Press any key to continue

==================================
结论:
就像C++ Primer中写到的一样,如果你不显示提供一个copy ctor,那么编译器使用bitwise copy完成copy ctor功能,由于该操作极为简便,因此编译器不会进行优化,需要的时候就进行此操作,因此第一段代码的运行结果是调用了3次copy ctor。
如果你自己定义了copy ctor,编译器会认为:我的用户自己定制了copy ctor,八成要做什么复杂工作吧,每次copy出一个对象来都得费不少事,那么我还是为他/她进行优化吧。因此第二段代码仅仅调用了1次copy ctor。

P.S.:测试环境是VC6,如果改用G++编译器的话,我试验了一下,结论就不像前述所说的那样了,各个编译器有各自的优化策略,总之。

但VC6里面较好的体现出了Lippman的思想。

posted on 2008-12-15 22:59 so true 阅读(482) 评论(0)  编辑  收藏 所属分类: C&C++


只有注册用户登录后才能发表评论。


网站导航: