c++智能指针(smart pointer)详解

Smart Pointer

Deal with c++11’s smart pointer facility.

brief

Smart pointers are class objects that behave like built-in pointers but also manage objects that you create with new so that you don’t have to worry about when and whether to delete them - the smart pointers automatically delete the
managed object for you at the appropriate time.

  • shared_ptr
  • weak_ptr
  • unique_ptr

shared_ptr (共享指针)

  • referenced-counted smart pointer
  • Shared Ownership with shared_ptr

引用计数智能指针:可以和其他 boost::shared_ptr 类型的智能指针共享所有权。 在这种情况下,当引用对象的最后一个智能指针销毁后或者被重新赋值或者使用了reset(),对象才会被释放。多个shared_ptr对象可以拥有同一个对象。

在继承中的例子:

    shared_ptr<Thing> base_ptr(new Thing(2));
    shared_ptr<Food> derived_ptr;
    ///if static_cast<Derived* >(base_ptr.get()) is valid, then the following is valid:
    base_ptr->showID();

    ///cast failed
    derived_ptr = static_pointer_cast<Food>(base_ptr);

    shared_ptr<Food> a(new Food);
//    a->showID();

    derived_ptr->showID();

使用 make_shared 更加高效

There are actually two dynamic memory allocations that happen: one for the object itself from the new, and then a second for the manager object created by the shared_ptr constructor. Since memory allocations are slow, this means that creating a shared_ptr is slow relative to using either a raw pointer, or a so-called “intrusive” reference- counted smart pointer where the reference count is a member variable of the object. To address this problem, C++11 includes a fun

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值