【发布时间】:2015-08-28 04:20:26
【问题描述】:
考虑以下代码:
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_from_this 返回 shared_ptr 给成员有什么问题吗?
【问题讨论】:
标签: c++ c++11 std shared-ptr