enable_shared_from_this - 空内部弱指针? [英] enable_shared_from_this - empty internal weak pointer?

查看:262
本文介绍了enable_shared_from_this - 空内部弱指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 enable_shared_from_this<基地以及GT; ,然后从基本继承。当试图使用 shared_from_this()派生的构造(未初始化列表),我得到一个异常。原来,该内部弱指针为空,并在所有没有指向这个。这怎么可能发生?我的其他使用案例正是这种工作完全正常。我甚至不知道从哪里开始。我低头看了看 enable_shared_from_this 来源$ C ​​$ C,它看起来对我来说,该指针将始终nullptr。

I'm using enable_shared_from_this<Base> and then inherit from Base. When trying to use shared_from_this() in Derived's constructor (not initializer list), I get an exception. Turns out that the internal weak pointer is null and doesn't point to this at all. How can this happen? My other use case of exactly this works perfectly fine. I don't even know where to start. I looked down at the source code of enable_shared_from_this, and it looks to me like that pointer would always be nullptr.

推荐答案

在对象的构造。 shared_from_this()要求对象由至少一个的shared_ptr 拥有。一个对象不能由所拥有的shared_ptr 它的构造了。

You cannot call shared_from_this() in the object's constructor. shared_from_this() requires that the object is owned by at least one shared_ptr. An object cannot be owned by a shared_ptr before it is constructed.

我猜想,当的shared_ptr 取对象的所有权首次内部弱指针设置。这点之前,没有引用计数结构的弱指针可以参考一下。

I would guess that the internal weak pointer is set when a shared_ptr takes ownership of the object for the first time. Before that point, there is no reference count struct that the weak pointer can reference.

这篇关于enable_shared_from_this - 空内部弱指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆