- 智能指针本质上是一个模板类,一般使用的这个类的对象,而不是指针
- 智能指针体现在内存释放问题上,用智能指针管理new的对象,将不在需要手动delete
- shared_ptr
get()函数:返回数据的指针的引用
use_count() : 返回管理对象的智能指针个数
swap() : 交换两个智能指针管理的对象
reset() : 重置智能指针对象
针对部分场景需要自己手动添加删除器去释放对象内存 - weak_ptr
以下对于三种类型分别举例:
- shared_ptr
#include#include #include using namespace std; class MyPerson { public: MyPerson(int age) :age(age) { cout << "MyPerson构造函数被调用!" << endl; } MyPerson() { cout << "MyPerson无参构造函数被调用" << endl; } ~MyPerson() { cout << "MyPerson析构函数被调用!" << endl; } void print() { cout << "MyPerson的年龄:" << age << endl; } private: int age; }; //这里智能指针类对象作为入参,会发送拷贝构造所以use_count智能指针数会+1 //如果传入引用就不会到导致use_count增加 void printPersonData(shared_ptr pMyPerson) { pMyPerson->print(); cout << "管理MyPerson对象的指针数:" << pMyPerson.use_count() << endl; } int main() { //针对基本数据类型 shared_ptr pInt(new int(111)); //访问数据 cout << *pInt << endl; cout << "使用get()获取数据:" << *pInt.get() << endl; //use_count返回对象的指针数 cout << "管理对象的指针数:" << pInt.use_count() << endl; shared_ptr pInt2(pInt); //使用拷贝构造函数 cout << "管理对象的指针数:" << pInt.use_count() << endl; cout << "管理对象的指针数:" << pInt2.use_count() << endl; shared_ptr pInt3; if (!pInt3) { cout << "空智能指针对象" << endl; } pInt3 = pInt2; cout << "管理对象的指针数:" << pInt3.use_count() << endl; //使用swap交换两个智能指针对象 shared_ptr aa(new int(11)); shared_ptr bb(new int(22)); aa.swap(bb); cout << "交换后" << endl; cout << "aa=" << *aa << "tbb=" << *bb << endl; bb.reset(new int(123)); //重置 cout << "*bb=" << *bb << endl; //针对自定义数据类型 //初始化 shared_ptr pMyPerson(new MyPerson(10)); //访问数据 pMyPerson->print(); cout << "管理MyPerson对象的指针数:" << pMyPerson.use_count() << endl; printPersonData(pMyPerson); //shared_ptr智能指针管理的对象会自动释放内存 system("pause"); return 0; }
结果分析:
1、使用shared_ptr智能指针管理自定义对象可以使用->访问对象的成员函数(shared_ptr智能指针类内部实现了重定义operator->)
2、使用shared_ptr智能指针管理的对象会自动释放内存,无需手动释放(针对于new创建内存)
3、使用use_count()返回管理对象的智能指针个数
111 使用get()获取数据:111 管理对象的指针数:1 管理对象的指针数:2 管理对象的指针数:2 空智能指针对象 管理对象的指针数:3 交换后 aa=22 bb=11 *bb=123 MyPerson构造函数被调用! MyPerson的年龄:10 管理MyPerson对象的指针数:1 MyPerson的年龄:10 管理MyPerson对象的指针数:2
针对如下场景
不支持创建连续内存 shared_ptrpMyPerson2(new MyPerson(10)[4]);
如果想要实现上面常见则自己需要在创建智能指针对象类时添加删除器(自己手动写释放内存过程)`
//带删除器写法; 自己写释放内存过程 shared_ptrpMyPerson2(new MyPerson[4], [](MyPerson* array) {delete[] array; });



