Smart pointer



       A smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic memory management or bounds checking. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency. Smart pointers typically keep track of the memory they point to. They may also be used to manage other resources, such as network connections and file handles.

       Smart pointers prevent most situations of memory leaks by making the memory deallocation automatic.More generally, they make object destruction automatic: the object controlled by a smart pointer is automatically destroyed (finalized and then deallocated) when the last (or only) owner of the object is destroyed.

      Smart pointers also eliminate dangling pointers by postponing destruction until the object is no longer in use.

      Several types of smart pointers exist. Some work with reference counting, others by assigning ownership of the object to a single pointer. If the language supports automatic garbage collection (for instance, Java or C#), then smart pointers are unnecessary for memory management, but may still be useful in resource management of other resources, such as file handles or network sockets

      Smart pointers can facilitate intentional programming by expressing the use of a pointer in the type itself. For example, if a C++ function returns a pointer, there is no way to know whether the caller should delete the memory pointed to when the caller is finished with the information.

some_type* ambiguous_function(); // What should be done with the result?

      Traditionally, this has been solved with comments, but this can be error-prone. The potential problems associated with this use can be mitigated by instead returning a unique_ptr,

unique_ptr<some_type> obvious_function1();

      The function makes explicit that the caller will take ownership of the result. Furthermore, no memory will be leaked if the caller does nothing. Prior to C++11, unique_ptr can be replaced with auto_ptr.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值