#include <iostream>
#include <memory>
using namespace std;
class Person
{
public:
Person()
{
cout << "Person()构造" << endl;
}
~Person()
{
cout << "~Person()析构" << endl;
}
Person(const Person &p)
{
cout << "Person()拷贝构造" << endl;
this->name = p.name;
this->age = p.age;
}
const Person& getPerson()
{
return *this;
}
string name;
int age;
};
int main()
{
std::shared_ptr<Person> p2;
{
std::shared_ptr<Person> p1(new Person);
cout << p1.use_count() << endl;
cout << p1.get() << endl;
p2 = p1;
cout << p1.use_count() << endl;
}
{
cout << p2.use_count() << endl;
cout << p2 << endl;
p2.reset();
cout << p2.use_count() << endl;
}
return 0;
}
$ g++ shared_ptr.cpp -std=c++11
$ ./a.out
Person()构造
1
0x22ccc20
2
1
0x22ccc20
~Person()析构
0
标签:std,释放,name,age,Person,shared,ptr
From: https://www.cnblogs.com/zhangxuechao/p/16663314.html