Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么';t std::shared\u ptr的别名构造函数从\u初始化std::enabled\u shared\u这个?_C++_C++11_Std_Shared Ptr - Fatal编程技术网

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填充为所有者的生命周期是有帮助的。