#include<iostream> using namespace std; #include<memory> class test { public: test(int no) { this->no = no; cout << "调用构造函数: " << no << endl; } ~test() { cout << "调用析构函数: " << no << endl; } private: int no; };
构造方式一:
shared_ptr<test>sp; shared_ptr<test>sp2(new test(1)); //use_count :当前管控同一个对象的智能指针对象 cout<<"sp.use_count:" << sp.use_count() << endl;//0 cout<<"sp2.use_count:" << sp2.use_count() << endl;//1 sp = sp2; cout << "----sp = sp2----" << endl; cout << "sp.use_count:" << sp.use_count() << endl;//2 cout << "sp2.use_count:" << sp2.use_count() << endl;//2 shared_ptr<test>sp3(sp); cout << "---shared_ptr<test>sp3(sp)---" << endl; cout << "sp.use_count:" << sp.use_count() << endl;//3 cout << "sp2.use_count:" << sp2.use_count() << endl;//3 cout << "sp3.use_count:" << sp3.use_count() << endl;//3 //sp.use_count() == sp2.use_count() == sp3.use_count() system("pause");
结果:
构造方式二: C++17之后支持
//数组对象管理 shared_ptr<test[]>arr(new test[5]{ 11, 22, 33, 44, 55 });
结果:
构造方式三:
//仿函数 class DestructTest { public: void operator()(test* t) { cout << "调用DestructTest... " << endl; delete t; } };
shared_ptr<test>sp(new test(666), DestructTest());
使用make_shared初始化对象,分配内存效率更高
//使用make_shared初始化对象,分配内存效率更高 // make_shared<类型>(参数) shared_ptr<string>s = make_shared<string>("ABC"); shared_ptr<string>s2; s2 = make_shared<string>("abc");
主动释放对象:
//主动释放对象 shared_ptr<string>s = make_shared<string>("ABC"); s = NULL; //或 // s = nullptr;
重置:
交换: