C++中用函数返回值初始类对象时的一个问题

来源:互联网 发布:微商比淘宝价格贵在哪 编辑:程序博客网 时间:2024/05/06 11:37
问题:
有一个类,名字是C,假设有一个函数,它的定义为:
[cpp] view plaincopy
  1. C func()  
  2. {  
  3.      C tmp;  
  4.      return tmp;  
  5. }  

即返回C类型的函数,那么考虑表达式C newC = func();将调用几次构造函数?分别是什么类型的构造函数?


解答:
<<C++ primer>>里有提到这个过程,首先会创建一个临时的类对象,该对象是由复制构造函数生成,参数是tmp。然后再调用复制构造函数初始化newC。所以一共调用了两次复制构造函数。
但现在的gcc不这么处理,会做一个优化。在C函数里有个tmp变量,离开func时不撤销这个对象,而是让newC和这个对象关联起来。也就是说tmp的地址和newC是一样的。


实验:
[cpp] view plaincopy
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class test  
  5. {  
  6. private:  
  7.     int num;  
  8.     static int total ;  
  9.   
  10. public:  
  11.     test()  
  12.     {  
  13.         num = 0 ;  
  14.         cout << "in the default constructor\n" ;  
  15.         total ++;  
  16.     }  
  17.     test(const test& a )  
  18.     {  
  19.         num = a. num;  
  20.         cout << "in the copy constructor\n" ;  
  21.         total ++;  
  22.     }  
  23.   
  24.     test(int a)  
  25.     {  
  26.         num = a;  
  27.         cout << "in the one-para constructor\n" ;  
  28.         total ++;  
  29.     }  
  30.   
  31.     test& operator=(const test& a )  
  32.     {  
  33.         num = a. num;  
  34.         cout << "in the assign op\n" ;  
  35.         return * this;  
  36.     }  
  37.   
  38.   
  39.     static void print ()  
  40.     {  
  41.         cout << total << endl;  
  42.     }  
  43.   
  44.     int showa ()  
  45.     {  
  46.        return num;  
  47.     }  
  48.   
  49. };  
  50.   
  51. int test:: total = 0;  
  52.   
  53. test testfunc(test t )  
  54. {  
  55.     cout << "1\n";  
  56.     test tmp(5 );  
  57.     cout << "address of tmp:" << &tmp << endl ;  
  58.     cout << "2\n";  
  59.     return tmp ;  
  60. }  
  61.   
  62. int main()  
  63. {  
  64.   
  65.     test para;  
  66.     test result = testfunc (para);  
  67.   
  68.     cout << "address of result:" << &result << endl ;  
  69.     cout << "result.a = " << result.showa () << endl;  
  70.   
  71.     cout << "3\n";  
  72.     test::print ();  
  73.   
  74.     return 0;  
  75. }  

那个static变量用来记录一共调用了几次构造函数。


结果:


解释:
第1行是因为test para;调用了默认构造函数。
第2行是因为把para传给函数形参调用了赋值构造函数。
第3行表明进入了testfunc()
第4行tmp调用参数为int的构造函数
第5行输出tmp的地址
第6行表明要离开函数
第7行输出result的地址,发现和tmp的地址是一样的
0 0
原创粉丝点击