shared_ptr 智能指针允许多个对象共享资源指向一个资源,指针里面含有引用计数,当引用计数为0时自动调用析构函数释放内存空间,因此可以自动释放动态内存空间。下面时一些简单的使用和介绍
#include<iostream>
#include<memory>
#include<vector>
using namespace std;
struct data
{
string name;
int age;
};
int main()
{
int a = 4;
shared_ptr<int>shared1 = make_shared<int>(a);
cout << "初始值是 " << *shared1 << endl;
cout << "使用计数 " << shared1.use_count() << endl;
shared_ptr<int>shared2 = shared1;
shared_ptr<int>shared3(shared2);
cout << "shared1 引用计数 " << shared1.use_count() << endl;
cout << "shared2 引用计数 " << shared2.use_count() << endl;
cout << "shared3 引用计数 " << shared3.use_count() << endl;
shared1.reset();
cout << "shared1 引用计数 " << shared1.use_count() << endl;
shared2.reset(new int(34));
cout << "shared2 引用计数 " << shared2.use_count() << endl;
cout << "shared3 引用计数 " << shared3.use_count() << endl;
shared_ptr<int>shared4 ;
if (shared4 == nullptr)
cout << " shared 4 is empty!!" << endl;
int* testdata = new int(10);
shared_ptr<int>shared5 (testdata);
shared_ptr<int>shared6(testdata);
shared_ptr<int>shared7 =shared6;
}
|