锂 さんのプロフィール向锂的Spaceフォトブログリスト ツール ヘルプ

ブログ


5月26日

幽默的编译器

在VC++6.0下面编译运行下面的代码,考察构造函数的执行,结果十分有意思,哈哈,编译器真是很搞很强大吐舌
 
#include<iostream.h>
class A{
public:
 A(int i ){
  aa ++ ;
  v = aa;
  cout<<"constructor is called for "<<v<<endl;
 }
 A(A& a){
  aa ++;
  v = aa;
  cout<<"copy constructor is called for "<<v<<endl;
 }
 ~A(){
  cout<<"deconstructor is called for "<<v<<endl;
 }
 int v;
private:
 static int aa;
};
int A::aa=0;
A func(A& a){
 cout<<"the begin of func"<<endl;
 A b(a);
 cout<<"before return b"<<endl;
 return b;
 
}
void func2(A a){
}
 
void main(){
 A x(1);
 cout<<"pause-1"<<endl<<endl;
 A y=func(x);
 cout<<"pause0"<<endl<<endl;
 A z = y;
 cout<<"pause1"<<endl<<endl;
 A& j =func(z);
 cout<<"pause2"<<endl<<endl;
 func2(z);
 cout<<"pause3"<<endl<<endl;
 z = x;
 cout<<"pause4"<<endl<<endl; 
}
 
运行结果如下,很有趣吧!大笑
constructor is called for 1
pause-1
the begin of func
copy constructor is called for 2
before return b
copy constructor is called for 3
deconstructor is called for 2
pause0
copy constructor is called for 4
pause1
the begin of func
copy constructor is called for 5
before return b
copy constructor is called for 6
deconstructor is called for 5
pause2
copy constructor is called for 7
deconstructor is called for 7
pause3
pause4
deconstructor is called for 6
deconstructor is called for 1
deconstructor is called for 3
deconstructor is called for 1