C++ 为什么';t std::shared\u ptr的别名构造函数从\u初始化std::enabled\u shared\u这个?
考虑以下代码:C++ 为什么';t std::shared\u ptr的别名构造函数从\u初始化std::enabled\u shared\u这个?,c++,c++11,std,shared-ptr,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> fo
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
}
struct Foo:std::从\u中启用\u共享\u
{
};
结构条
{
富富,;
};
int main()
{
std::共享条(新条);
//使用别名构造函数将共享\u ptr设置为成员
std::shared_ptr foo_p(bar_p和bar_p->foo);
assert(bar_p->foo.shared_from_this());//失败!抛出坏的\u弱的\u ptr
}
不幸的是,它没有按预期工作(至少在GCC 4.8.2中是这样)。我研究了代码,似乎别名构造函数根本就没有从\u this\u helper()调用\u enable\u shared\u
,这是从\u this()调用shared\u的正确工作所必需的
有人知道为什么它是这样设计的吗?将shared\u ptr从shared\u从\u this返回给成员是否有问题?[util.smartptr.shared.const]
template shared_ptr(const shared_ptr&r,T*p)无例外代码>
效果:构造一个共享的\u ptr
实例,该实例存储
,并与r
共享所有权
调用别名构造函数时,foo\u p
不拥有bar\u p->foo
的所有权,在本例中这是一件非常好的事情,因为否则它会尝试在销毁时删除它
[util.smartptr.enab]
shared_ptr shared_from_this()代码>
shared_ptr shared_from_this()const代码>
要求:[……]至少应有一个拥有&t
的共享\u ptr
实例p
由于bar\u p->foo
不属于至少一个shared\u ptr
的所有,您最终会出现未定义的行为,gcc抛出bad\u-weak\u ptr
,但它没有义务做任何有帮助的事情。好的,这就是行为,但其原理是什么?为什么shared\u from_this()
不要求至少有一个shared\u ptr
存储p
?因为根本无法统计谁拥有一个原始指针以及它打算用它做什么,你似乎认为shared\u ptr
知道或关心p
的生命周期,更不用说它是一个层次结构的一部分,可能涉及也可能不涉及另一个shared\u ptr
实例。我假设,只有当r
保证了它的p
生命周期时,才能正确使用shared\u ptr的别名构造函数(就像p
指向r
指向的结构成员的情况一样)。在这种情况下,shared_ptr
间接关心p
的生命周期。在其他情况下,shared\u ptr
无论如何都是无效的。我支持peper0。我看不出有任何技术上的理由不能做到这一点@user657267:别名构造函数确实与r
共享控制块,这是我们关心的生命周期,因为p
的生命周期直接与r
相关。我认为将p的shared_from_this填充为所有者的生命周期是有帮助的。