繁体   English   中英

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

[英]Why doesn't aliasing constructor of std::shared_ptr initialize std::enabled_shared_from_this?

请考虑以下代码:

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

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

[util.smartptr.shared.const]

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

效果:构造一个shared_ptr实例,该实例存储 p并与r 共享所有权

foo_p不带任何的所有权bar_p->foo当你调用走样构造,在这种情况下是一件非常好的事情,因为否则它会尝试delete它破坏。

[util.smartptr.enab]

shared_ptr<T> shared_from_this();

shared_ptr<T const> shared_from_this() const;

要求:[...]至少应有一个拥有&t shared_ptr实例p。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM