- C++智能指针shared_ptr实现的是,多个指针指向相同的对象,其释放的时机是最后一个引用被销毁时,当use_count()为0时被彻底释放。
- 我们可以调用release()释放资源所有权,计数减一。
- shared_ptr容易引起死锁。
- 避免使用raw pointer
#include<iostream>
#include<memory>
using namespace std;
class Dog{
public:
Dog(){
cout<<"Nameless dog created."<<endl;
s1="nameless";
}
Dog(string name){
cout<<"Dog is created:" << name<<endl;
s1=name;
}
void foo(){
cout<<"Dog "<<s1<<" rules. "<<endl;
}
~Dog(){
cout<<"Dog is destoryed:"<<s1<<endl;
}
private:
string s1;
};
void test()
{
shared_ptr<Dog> p=make_shared<Dog>("jinmao");
cout<<p.use_count()<<endl;
{
shared_ptr<Dog> p1=p;
cout<<p.use_count()<<endl;
p1->foo();
cout<<p.use_count()<<endl;
}
p->foo();
}
int main()
{
test();
return 0;
}