为什么没有std :: shared_ptr的别名构造函数初始化std :: enabled_shared_from_this?

时间:2015-06-12 08:07:22

标签: c++ c++11 std shared-ptr

请考虑以下代码:

struct Foo : std::enable_shared_from_this<Foo>
{

};

struct Bar
{
    Foo foo;
};

int main()
{
    std::shared_ptr<Bar> bar_p(new Bar);

    //make shared_ptr to member with aliasing constructor
    std::shared_ptr<Foo> foo_p(bar_p, &bar_p->foo);
    assert(bar_p->foo.shared_from_this()); //fail! throws bad_weak_ptr
}

不幸的是,它没有按预期工作(至少在GCC 4.8.2中)。我查看了代码,似乎别名构造函数根本不会调用__enable_shared_from_this_helper() shared_from_this()的正常工作所必需的。{/ p>

有人知道为什么它是以这种方式设计的吗?将shared_ptr从shared_from_this返回给成员有什么问题吗?

1 个答案:

答案 0 :(得分:6)

[util.smartptr.shared.const]

  

template<class Y> shared_ptr(const shared_ptr<Y>& r, T* p) noexcept;

     

效果:构建{strong>商店 shared_ptr共享所有权 p实例与r

当你调用别名构造函数时,

foo_p没有bar_p->foo的所有权,在这种情况下,它是非常好东西,否则会尝试{{1}它在毁灭中。

[util.smartptr.enab]

  

delete

     

shared_ptr<T> shared_from_this();

     

要求:[...]至少应有一个拥有shared_ptr<T const> shared_from_this() const;的{​​{1}}个实例p。

由于shared_ptr不属于至少一个&t,您最终会遇到未定义的行为,因此gcc会抛出bar_p->foo,但它没有义务做任何有用的事情。

相关问题