[英]QEnableSharedFromThis::sharedFromThis() returns nullptr
I have a class MyClass
that should be able to return this wrapped in QSharedPointer<MyClass>
. 我有一个
class MyClass
,应该可以将其包装在QSharedPointer<MyClass>
。
It is my understanding (and experience) that simply creating new instances of QSharedPointer<MyClass>(this)
is NOT the way to go. 根据我的理解(和经验),简单地创建
QSharedPointer<MyClass>(this)
新实例是QSharedPointer<MyClass>(this)
。 Instead The correct way to accomplish what I want is to let MyClass
inherit from QEnableSharedFromThis<MyClass>
to provide the member function sharedFromThis()
. 相反,完成我想要的操作的正确方法是让
MyClass
从QEnableSharedFromThis<MyClass>
继承以提供成员函数sharedFromThis()
。
This member function should return this wrapped in QSharedPointer<MyClass>
without all the bad side effects that would otherwise occur. 该成员函数返回这个包裹在
QSharedPointer<MyClass>
没有所有的不良副作用可能发生的。
class MyClass : public QEnableSharedFromThis<MyClass>
{
/* ... */
public:
void testSharedThis()
{
auto sp=QEnableSharedFromThis<MyClass>::sharedFromThis();
if(sp.isNull()){
qWarning()<<"SHARED POINTER TO *this* WAS NULL!";
}
}
};
void main(){
MyClass *mc=new MyClass;
mc->testSharedThis();
}
However when I run testSharedThis()
in the example above, sharedFromThis()
always returns nullptr instead of this wrapped in QSharedPointer<MyClass>
. 但是,当我在上面的示例中运行
testSharedThis()
时, sharedFromThis()
始终返回nullptr而不是将其包装在QSharedPointer<MyClass>
。
I am new to QEnableSharedFromThis
and I am wondering if there is something that I am missing, or what could be the cause of this? 我是
QEnableSharedFromThis
,我想知道是否丢失了某些东西,或者可能是什么原因引起的?
According to the official documentation: 根据官方文件:
A base class that allows obtaining a QSharedPointer for an object already managed by a shared pointer.
一个基类,允许为已经由共享指针管理的对象获取QSharedPointer。 You can inherit this class when you need to create a QSharedPointer from any instance of a class;
当需要从任何类的实例创建QSharedPointer时,可以继承该类。 for instance, from within the object itself.
例如,从对象本身内部。
So you need to instantiate your pointer as smart pointer: 因此,您需要将您的指针实例化为智能指针:
QSharedPointer<MyClass> mc(new MyClass());
mc->testSharedThis();
Or in your case use the equivalent to std::make_shared for Qt Smart Pointers: 或者在您的情况下,将等效于std :: make_shared用于Qt智能指针:
QSharedPointer<MyClass> mc = QSharedPointer<MyClass>::create();
mc->testSharedThis();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.