标签:ios class bsp size share cpp 引用计数 mes 自动
当进行拷贝或赋值操作时,每个shared_ptr都会纪录有多少个其他shared_ptr指向相同的对象:
auto p = make_shared<int>(50);//p指向的对象只有p一个引用者
auto q = p; //p和q指向相同对象,此对象有两个引用者;
智能指针类能记录有多少个shared_ptr指向相同的对象,并能在恰当的时候自动释放对象!
关于shared_ptr的引用计数测试demo:
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
int main()
{
vector<shared_ptr<int>> intPtr;
vector<shared_ptr<int>> intPtr2;
for (int i = 0; i < 10; ++i) {
intPtr.emplace_back(make_shared<int>(i));
}
for (int i = 0; i < 10; ++i) {
cout << "intPtr " << i << " = " << *intPtr.at(i) << endl;
}
intPtr2 = intPtr;
/*
cout << "2: intPtr[0].use_count() = " << intPtr[0].use_count() << endl;
cout << "2: intPtr2[0].use_count() = " << intPtr2[0].use_count() << endl;
*/
cout << "intPtr[0] = " << intPtr[0] << endl;
cout << "intPtr2[0] = " << intPtr2[0] << endl;
intPtr[0] = make_shared<int>(50);
cout << "3: intPtr[0].use_count() = " << intPtr[0].use_count() << endl;
cout << "3: intPtr2[0].use_count() = " << intPtr2[0].use_count() << endl;
cout << "intPtr[0] = " << intPtr[0] << endl;
cout << "intPtr2[0] = " << intPtr2[0] << endl;
cout << "intPtr[0] = " << *intPtr[0] << endl;
cout << "intPtr2[0] = " << *intPtr2[0] << endl;
return 0;
}
标签:ios class bsp size share cpp 引用计数 mes 自动
原文地址:https://www.cnblogs.com/create-serenditipy/p/13393511.html