代码之家  ›  专栏  ›  技术社区  ›  sorush-r

“std::shared\u ptr”的别名构造函数的用法是什么`

  •  0
  • sorush-r  · 技术社区  · 4 年前

    http://www.cplusplus.com/reference/memory/shared_ptr/ ),第5段,它说:

    此外,共享的ptr对象可以在指向另一个对象的同时共享指针的所有权。这种能力称为别名(请参阅构造函数),通常用于在拥有成员对象所属的对象时指向成员对象。因此,共享的指针可能与两个指针有关:

    • 一个存储的指针,它被称为指向的指针,它与运算符*取消引用。

    • 一个拥有的指针(可能是共享的),它是所有权组负责在某个点上删除的指针,并将其作为一个使用。

    但是别名共享的ptr对象(那些用别名构造函数及其副本构造的对象)可能引用不同的对象

    然后我读了这一页( http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/ )关于shared\u ptr的别名构造函数。但我仍然认为这种“化名”行为令人困惑。 为什么在这里?这是干什么用的?在什么情况下我需要这个功能?

    0 回复  |  直到 9 年前
        1
  •  56
  •   Barry    5 年前

    简单示例:

    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);
    

    别名是指当我们真的想指向 Bar ,但我们也不想 Foo


    正如Johannes在评论中指出的那样,有一个相当的语言特征:

    Bar const& specific_data = Foo(...).bar;
    Bar&& also_specific_data = Foo(...).bar;
    

    我们指的是临时组织的成员,但是临时组织 只要你还活着 specific_data shared_ptr 例如,我们有一个 他的一生与 -a