课上临时想到的
就是类似第41行的赋值语句,会生成一个临时变量(其它代码不用管)
经过实验发现
这个临时变量的生命周期只限于这个语句,语句结束后就会调用析构函数
而且如果写成
- kk::a d=kk::a(b);
则不会看见这个临时变量的生成,估计被编译器给优化掉了
- #include <iostream>
- using namespace std;
- namespace kk
- {
- int count=1;
- class a
- {
- public:
- int counts;
- a();
- ~a();
- a(const a&);
- };
- }
- kk::a::a()
- {
- counts=kk::count;
- cout<<"creat the"<<counts<<"th instance"<<"from creat"<<endl;
- kk::count++;
- }
- kk::a::a(const a& b)
- {
- counts=kk::count;
- cout<<"creat the"<<counts<<"th instance"<<" from copy"<<endl;
- kk::count++;
- }
- kk::a::~a()
- {
- cout<<"delete the"<<counts<<"th instance"<<endl;
- }
- void kkk()
- { kk::a b;
- cout<<b.counts<<endl;
- kk::a c(b);
- cout<<c.counts<<endl;
- kk::a d;
- cout<<d.counts<<endl;
- d=kk::a(b);
- d.counts=3;
- }
- int main()
- {
- kkk();
- char sss;
- cin>>sss;
- }
本文出自 “DarkScope从这里开始(..” 博客,请务必保留此出处http://darkscope.blog.51cto.com/4254649/1005164