QPointer对象的实现如下,其中我们可以看到,QPointer在构造时,模板类型不能是指针(通过c++的偏特化特性来判断是否传入类型为指针)。其次是对象的成员QWeakPointer,QPointer是对QWeakPointer进行封装,使得QWeakPointer比较简单易用。因此,在探寻QPointer为啥能够在QObject析构时,自动置为nullptr,其实底层原理实际在QWeakPointer中实现。
class QPointer
{
Q_STATIC_ASSERT_X(!std::is_pointer<T>::value, "QPointer's template type must not be a pointer type");
...
QWeakPointer<QObjectType> wp;
public:
inline QPointer() { }
inline QPointer(T *p) : wp(p, true) { }
...
};
QPointer构造一个指针对象时,QWeakPointer调用的构造函数为
inline QWeakPointer(X *ptr, bool) : d(ptr ? Data::getAndRef(ptr) : nullptr), value(ptr)
Data::getAndRef的具体实现如下,获取ptr对象的引用计算,返回弱引用指针:
QtSharedPointer::ExternalRefCountData *QtSharedPointer::ExternalRefCountData::getAndRef(const QObject *obj)
{
Q_ASSERT(obj);
QObjectPrivate *d = QObjectPrivate::get(const_cast<QObject *>(obj));
Q_ASSERT_X(!d->wasDeleted, "QWeakPointer", "Detected QWeakPointer creation in a QObject being deleted");
ExternalRefCountData *that = d->sharedRefcount.load();
if (that) {
that->weakref.ref();
return that;
}
// we can create the refcount data because it doesn't exist
ExternalRefCountData *x = new ExternalRefCountData(Qt::Uninitialized);
x->strongref.store(-1);
x->weakref.store(2); // the QWeakPointer that called us plus the QObject itself
ExternalRefCountData *ret;
if (d->sharedRefcount.testAndSetOrdered(nullptr, x, ret)) { // ought to be release+acquire; this is acq_rel+acquire
ret = x;
} else {
// ~ExternalRefCountData has a Q_ASSERT, so we use this trick to
// only execute this if Q_ASSERTs are enabled
Q_ASSERT((x->weakref.store(0), true));
delete x;
ret->weakref.ref();
}
return ret;
}
QWeakPointer的默认构造会自动置nullptr,因此,使用QPointer作为成员变量时,不需要额外初始化为nullptr
inline QPointer() { }
inline QWeakPointer() Q_DECL_NOTHROW : d(nullptr), value(nullptr) { }
QSharedPointer中的引用计数对象也是ExternalRefCountData,QObjectPrivate中的ExternalRefCountData和QSharedPointer中记录对象的ExternalRefCountData有一些区别,尽管它们的用途和机制都与引用计数有关。
1. QObjectPrivate::ExternalRefCountData
QObjectPrivate 中的 ExternalRefCountData 是 QObject 用来管理其外部引用计数的结构。QObject 对象的外部引用计数用于管理对象的生命周期,特别是在对象被外部引用时防止其被过早删除。这个引用计数主要与事件循环、信号槽机制以及一些特殊的QObject派生类相关联。
QObjectPrivate 中的 ExternalRefCountData 通过引用计数跟踪外部对该 QObject 的引用。当引用计数为0时,QObject 可以安全地销毁。
这部分机制主要是在Qt的内存管理和QObject生命周期管理中起作用。2. QSharedPointer::ExternalRefCountData
QSharedPointer 中的 ExternalRefCountData 是智能指针机制的一部分,用于管理指针的引用计数。QSharedPointer 是一个智能指针类,提供了自动的内存管理,通过引用计数来决定对象的删除时间。
当多个 QSharedPointer 指向同一对象时,这个对象的引用计数会增加。只有当最后一个 QSharedPointer 被销毁或者重置时,指向的对象才会被删除。
QSharedPointer::ExternalRefCountData 管理的引用计数不仅仅是对象本身的引用,还包括指向同一对象的所有 QSharedPointer 实例的引用。
QWeakPointer获取所指对象QObjectPrivate的弱引用,对象指针获取和判空时,都会 d->strongref.load()判断所指对象的强引用计数,通过强引用计数来判断对象是否还存在。
bool isNull() const Q_DECL_NOTHROW { return d == nullptr || d->strongref.load() == 0 || value == nullptr; }
T *data() const Q_DECL_NOTHROW { return d == nullptr || d->strongref.load() == 0 ? nullptr : value; }
那么,QObjectPrivate中的sharedRefcount是怎么维护的呢?
在QObject::~QObject()中,会获取QObjectPrivate中的sharedRefcount,并且设置 sharedRefcount->strongref.store(0)为0,QWeakPointers在跟踪这个对象时,会通过判断strongref为0时来确认该对象是否被销毁,sharedRefcount的实际销毁时机在最后一个weakref.deref()时。
QtSharedPointer::ExternalRefCountData *sharedRefcount = d->sharedRefcount.load();
if (sharedRefcount) {
if (sharedRefcount->strongref.load() > 0) {
qWarning("QObject: shared QObject was deleted directly. The program is malformed and may crash.");
// but continue deleting, it's too late to stop anyway
}
// indicate to all QWeakPointers that this QObject has now been deleted
sharedRefcount->strongref.store(0);
if (!sharedRefcount->weakref.deref())
delete sharedRefcount;
}
inline ~QWeakPointer() { if (d && !d->weakref.deref()) delete d; }
因此,sharedRefcount->strongref.store(0),是QWeakPointer判断所指对象是否被销毁的依据,QObjectPrivate的ExternalRefCountData 在Data::getAndRef时被初始化,在QObject::~QObject()时,sharedRefcount->strongref.store(0),标记对象被销毁。通过引用计数的形式,进行对象跟踪。