Smart Pointers

Purpose

  Smart pointers, compared with raw pointers, have value semantics, which means we can freely create, copy and change it. However, consider the example:

Widget *p = new Widget();

You can not copy or assign this pointer at will because it will lead to memory leak.

std::unique_ptr

  1. A non-null std::unique_ptr always owns what it points to.
  2. Copying is not allowed but you can use move to transfer ownership to another pointer.
  3. Upon destruction, it destroys the resource.
  4. Same size of raw pointers

std::shared_ptr

  1. It can tell whether it is the last one pointing to a resource by consulting the resource’s reference count.
  2. Twice the size of raw pointers due to the use of reference count. Internally, shared_ptr contains a pointer to the resource and a pointer to the resource’s reference count.

std::weak_ptr

  1. Can not be dereferenced nor can they be tested for nullness
  2. Point to the same place as the std::shared_ptr initialize it, but they will not affect the reference count of the object they point to
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值