天天看点

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。

继续阅读