1、智能指针的作用
C++程序设计中使用堆内存是非常频繁的操作,堆内存的申请和释放都由程序员自己管理。程序员自己管理堆内存可以提高了程序的效率,但是整体来说堆内存的管理是麻烦的,智能指针的概念,方便管理堆内存。使用普通指针,容易造成堆内存泄露(忘记释放),二次释放,程序发生异常时内存泄露等问题等,使用智能指针能更好的管理堆内存。
从较浅的层面看,智能指针是利用了一种叫做RAII(资源获取即初始化)的技术对普通的指针进行封装,这使得智能指针实质是一个对象,行为表现的却像一个指针。
智能指针的作用是防止忘记调用delete释放内存和程序异常的进入catch块忘记释放内存。另外指针的释放时机也是非常有考究的,多次释放同一个指针会造成程序崩溃,这些都可以通过智能指针来解决。
2、std::shared_ptr
头文件:
#include <memory>
3、创建方法
std::shared_ptr<类型名>
4、初始化方法
一:创建对象初始化
Student *s1 = new Student(); std::shared_ptr<Student> s2(s1);二:使用make_shared初始化
std::shared_ptr<Student> sp3 = std::make_shared<Student>();
三:
std::shared_ptr<Student> sp4(new Student());
5、use_count()函数
返回引用计数的个数
std::shared_ptr<Student> sp(new Student()); sp.use_count();
6、unique()
返回是否独占所有权(use_count为1)
std::shared_ptr<Student> sp(new Student()); sp.unique();
7、swap() 交换对象
std::shared_ptr<Student> sp1(new Student()); std::shared_ptr<Student> sp2(new Student()); s1.swap(sp2);8、reset()
放弃内部对象的所有权或拥有对象的变更, 会引起原有对象的引用计数的减少
std::shared_ptr<Student> sp1(new Student()); sp1.reset();9、get()
返回内部对象,未找到返回空
sp.get();Demo:
#include <iostream> #include <memory> using namespace std; class Student { public: Student(){}; Student(int age){m_age = age;} ~Student(){ }; public: void print_age(){cout<<m_age<<endl;} private: int m_age; }; int main() { Student *sp1= new Student(20); std::shared_ptr<Student> sp2(sp1); std::shared_ptr<Student> sp3 = std::make_shared<Student>(20); //sp3->print_age(); std::shared_ptr<Student> sp4(new Student(10)); //sp4->print_age(); cout<<sp4.use_count()<<endl; std::shared_ptr<Student> sp5=sp4; std::shared_ptr<Student> sp6=sp4; cout<<sp4.use_count()<<endl; sp4.reset(); cout<<sp4.use_count()<<endl; return 0; }
结果:
g++ -o shared_test shared_test.cpp -std=c++0x ./shared_test 1 3 0参考:
https://blog.csdn.net/u011068702/article/details/83692838
https://www.cnblogs.com/diysoul/p/5930361.html
https://en.cppreference.com/w/cpp/memory/shared_ptr
