目录
智能指针
- 智能指针本质是一个模板类,一般使用的是这个类的对象,而不是指针
- 智能指针体现在内存释放问题,用智能指针管理new对象,将不在需要手动delete
- shared_ptr
- get()函数:返回数据的指针的引用
- use_count()函数:返回的是管理对象的智能指针对象数
- swap():交换管理对象
- reset():重置管理对象
#include<iostream> #include<memory> #include<string> #include<cstdio> using namespace std; class Rat { public: ~Rat() { cout << "析构函数" << endl; } void print() { } protected: }; void printData(shared_ptr<Rat>pRat) { cout << "调用printData函数:" << endl; cout << "管理对象的指针数:" << pRat.use_count() << endl; } void FreeFile(FILE* file) { free(file); } int main() { //基本用法 //new int(11)申请内存并做初始化 //做初始化 shared_ptr<int>pInt(new int(1)); //访问数据 cout << *pInt << endl; //shared_ptr<int>p=new int(2);错误 //自定义类型 shared_ptr<Rat>rat(new Rat); rat->print(); //成员get()函数 int* pData = pInt.get(); //user_count()函数 shared_ptr<int>ptr(new int(1)); cout <<"管理对象的指针数:"<< ptr.use_count() << endl; shared_ptr<int>bptr(ptr); cout << "管理对象的指针数:" << ptr.use_count() << endl; cout << "管理对象的指针数:" << bptr.use_count() << endl; shared_ptr<int>cptr=bptr; cout << "管理对象的指针数:" << cptr.use_count() << endl; //swap()函数和reset() shared_ptr<int>a(new int('a')); shared_ptr<int>b(new int('b')); a.swap(b); cout << "a:" << *a << " " << " b:" << *b << endl; cout << "管理对象的指针数:" << a.use_count() << endl; b.reset(new int('c')); cout << "b:" << *b << endl; { shared_ptr<Rat>prat(new Rat); cout << "........." << endl; cout << "管理对象的指针数:" << prat.use_count() << endl; printData(prat); } //带删除的写法 //删除器:理解为手动写释放内存的过程 { cout << "正常写法:" << endl; shared_ptr<Rat>J(new Rat, [](Rat* p) {delete p; }); } shared_ptr<FILE>pf(fopen("1.txt", "w"),FreeFile); return 0; }
- weak_ptr
- 弱引用指针,不会累计计数
- weak_ptr只能通过shared_ptr或者weak_ptr来构造
- 不能使用*取值只能用->来取值
#include<iostream> #include<memory> using namespace std; class Union { public: void print() { cout << "调用" << endl; } ~Union() { cout << "析构函数" << endl; } protected: }; class B; class A { public: A() { cout << "A" << endl; } ~A() { cout << "~A" << endl; } weak_ptr<B>b; protected: }; class B{ public: B() { cout << "B" << endl; } ~B() { cout << "~B" << endl; } weak_ptr<A>a; protected: }; void test() { shared_ptr<A>Aobject(new A); shared_ptr<B>Bobject(new B); Aobject->b = Bobject; Bobject->a = Aobject; cout << endl; } int main() { shared_ptr<Union>pa(new Union); shared_ptr<Union>pb = pa; cout << "计数:" << pb.use_count() << endl; weak_ptr<Union>pc(pa); cout << "计数:" << pb.use_count() << endl; //(*pc).print();weak_ptr不存在这种访问方式 pc.lock().get()->print(); pc.lock()->print(); test(); //make_shared管理自定义类型,参数个数由构造函数决定 shared_ptr<int>Pmake = make_shared<int>(12); cout << *Pmake<< endl; int* pp = Pmake.get(); //delete pp;手动析构会引发析构问题 return 0; }
unique_ptr
- 禁止拷贝和赋值,独占型
- 任何时候unique_ptr操作管理对象,永远只有一个有效
- 可以通过move函数转交所有权
- reset函数结合release函数