1.使用智能指针需要#include <memeroy>
2.上代码:
#include <memory>
#include <iostream>
using namespace std;
struct lifePeriod
{
lifePeriod():a(1)
{
cout << "无参构造!" << endl;
}
virtual ~lifePeriod()
{
cout << "析构!" << endl;
}
lifePeriod(const lifePeriod& d)
{
cout << "有参构造!" << endl;
}
int a;
};
int main()
{
{
shared_ptr<lifePeriod> p5 = make_shared<lifePeriod>();
cout << p5.use_count() << endl;
shared_ptr<lifePeriod> p6(p5);
shared_ptr<lifePeriod> p7(p6);
cout << p5.use_count() << endl;
cout << p6.use_count() << endl;
cout << p7.use_count() << endl;
}
cout << "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$-------------r$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" << endl;
}
无参构造!
1
3
3
3
析构!
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$-------------r$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
3.解释:放心使用的原因,智能指针本身是模板类,离开作用域会调用析构函数,将引用计数减1,最终引用计数都会为0,释放资源