C++ 那些被遗漏的细节5 shared_ptr别名构造函数

概述
  1. shared_ptr的基本使用可以参考之前文章: C++11 shared_ptr weak_ptr

  2. 别名构造函数

    // cppreference
    template< class T > class shared_ptr;(since C++11)
    // 别名构造函数
    template< class Y >
    shared_ptr( const shared_ptr<Y>& r, element_type* ptr ) noexcept;
    
  3. cplusplus上的解释

  • Additionally, shared_ptr objects can share ownership over a pointer while at the same time pointing to another object. This ability is known as aliasing (see constructors), and is commonly used to point to member objects while owning the object they belong to. Because of this, a shared_ptr may relate to two pointers:
    • A stored pointer, which is the pointer it is said to point to, and the one it dereferences with operator*.
    • An owned pointer (possibly shared), which is the pointer the ownership group is in charge of deleting at some point, and for which it counts as a use.
  • Generally, the stored pointer and the owned pointer refer to the same object, but alias shared_ptr objects (those constructed with the alias constructor and their copies) may refer to different objects.
  1. 例子

    struct Bar { 
        // some data that we want to point to
    };
    
    struct Foo {
        Bar bar;
    };
    
    shared_ptr<Foo> f = make_shared<Foo>(some, args, here);
    shared_ptr<Bar> specific_data(f, &f->bar);
    
    // ref count of the object pointed to by f is 2
    f.reset();
    
    // the Foo still exists (ref cnt == 1)
    // so our Bar pointer is still valid, and we can use it for stuff
    some_func_that_takes_bar(specific_data);
    
参考
  1. 语法请参见 cppreference
  2. 解释请参见 cplusplus
  3. 举例请参见 stackoverflow
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值