sharedptr引用计数
越甲八千 2020-10-22 04:44:48 #include <iostream>
#include<memory>
#include<string>
using namespace std;
int main()
{
auto p = make_shared<int>(42); //!指向的对象只有p一个引用者。
cout << p.use_count() << endl;
auto q = make_shared<int>(56);//!指向的对象只有q一个引用者。
cout << q.use_count() << endl;
cout << "---------afterAssin-----" << endl;
p = q; //!p原来引用的对象经过赋值之后释放掉了,q引用的对象有了p和q两个引用。
cout << *p << "==" << *q << endl;
cout << q.use_count() << endl;
cout << p.use_count() << endl;
}
输出结果:
1
1
-------- - afterAssin---- -
56 == 56
2
2
请按任意键继续. . .
问题:为何最后一个输出是2 而不是0