C++构造函数上的一点疑惑的解析

来源:互联网 发布:电魂网络合理市值 编辑:程序博客网 时间:2024/05/23 21:58

课上临时想到的

就是类似第41行的赋值语句,会生成一个临时变量(其它代码不用管)

经过实验发现

这个临时变量的生命周期只限于这个语句,语句结束后就会调用析构函数

而且如果写成

  1. kk::a d=kk::a(b);

则不会看见这个临时变量的生成,估计被编译器给优化掉了

  1. #include <iostream> 
  2. using namespace std; 
  3. namespace kk 
  4. int count=1; 
  5. class a 
  6. public
  7.       int counts; 
  8.       a(); 
  9.       ~a(); 
  10.       a(const a&); 
  11.  
  12.  
  13.       }; 
  14.       } 
  15. kk::a::a() 
  16. {      
  17.       counts=kk::count; 
  18.       cout<<"creat the"<<counts<<"th instance"<<"from creat"<<endl; 
  19.       kk::count++; 
  20.        
  21.       } 
  22. kk::a::a(const a& b) 
  23.      counts=kk::count; 
  24.       cout<<"creat the"<<counts<<"th instance"<<" from copy"<<endl; 
  25.       kk::count++;   
  26.           } 
  27. kk::a::~a() 
  28.        cout<<"delete the"<<counts<<"th instance"<<endl; 
  29.        } 
  30. void kkk() 
  31. {   kk::a b; 
  32.     cout<<b.counts<<endl;   
  33.     kk::a c(b); 
  34.     cout<<c.counts<<endl; 
  35.     kk::a d; 
  36.     cout<<d.counts<<endl; 
  37.     d=kk::a(b); 
  38.     d.counts=3; 
  39.      
  40. int main() 
  41.    kkk(); 
  42.    char sss; 
  43.    cin>>sss; 

 

本文出自 “DarkScope从这里开始(..” 博客,请务必保留此出处http://darkscope.blog.51cto.com/4254649/1005164

原创粉丝点击