share_prt类
share_prt 也是一个类模板,使用时和vector一样要说明类型。
shared_prt<string> p1; //这是一个指向string类型的智能指针,使用默认构造函数初始化智能指针,里面含有一个NULL指针。
智能指针的使用和普通指针一样,也是通过解引用返回一个对象的值
// if p1 is not null, check whether it's the empty string
if(p1 && p1->empty())
*p1 = "hi"; // if so, dereference p1 to assign a new value to that string
make_shared函数
make_shared函数为对象动态分配内存并初始化,return一个shared_prt类,来指向这个对象。
// shared_prt指向一个值为42的int型变量
shared_prt<int> p3 = make_shared<int>(42);
// p4 points to a string with value 9999999999
shared_prt<string> p4 = nake_shared<string>(10, '9');
// p5 points to an int that is value initialized to 0
shared_prt<int> p5 = make_shared<int>(); // 默认构造函数
// 使用auto去定义一个对象来存放make_shared的返回值
auto p6 = make_shared<vector<string>>();
shared_prt拷贝和赋值
当拷贝或者赋值一个shared_prt时,每一个shared_prt都会记录有多个shared_prt指向了同一个对象
auto p = make_shared<int>(42); //object to which p points has one user
auto q(p); // p and q point to the same object
// object to which p and q point has two users
auto r = make_shared<int>(42); //int to which r points has one user
r = q; // assign to r, making it point to a different address
// increase the use count for the object to which q points
// reduce the use count of the object to which r had pointed
// the object r had pointed to has no users; that object is automatically freed
自动释放内存
当在函数内部定义(即局部变量)了一个只能指针shared_prt,在函数结束的时候,会自动释放内存。当然啦,如果这个函数的返回类型是shared_prt,那么会发生一次只能指针拷贝的过程。