智能指针(Smart Pointers)

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,那么会发生一次只能指针拷贝的过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值