
QPointer 概述
QPointer 是一种受保护的指针,当其引用的对象被销毁时,它会被自动清除(但是,销毁引用对象还是必须手动 delete)。QPointer 所指向的对象必须是 QObject 或其派生类对象。当多个指针指向同一个 Object 对象时,引用的对象可能被释放掉,这时使用 QPointer 就可以安全的测试引用对象是否有效,防止发生指针空悬。QPointer 不管理指向对象的生命周期,但是能感知指向对象的生命周期,当指向对象被析构后,对应 QPointer 会被设置为 nullptr。
QPointer 源码
#ifndef QPOINTER_H
#define QPOINTER_H
#include <QtCore/qsharedpointer.h>
#include <QtCore/qtypeinfo.h>
#ifndef QT_NO_QOBJECT
QT_BEGIN_NAMESPACE
class QVariant;
template <class T>
class QPointer
{
Q_STATIC_ASSERT_X(!std::is_pointer<T>::value, "QPointer's template type must not be a pointer type");
template<typename U>
struct TypeSelector
{
typedef QObject Type;
};
template<typename U>
struct TypeSelector<const U>
{
typedef const QObject Type;
};
typedef typename TypeSelector<T>::Type QObjectType;
QWeakPointer<QObjectType> wp;
public:
inline QPointer() {
}
inline QPointer(T *p) : wp(p, true) {
}
// compiler-generated copy/move ctor/assignment operators are fine!
// compiler-generated dtor is fine!
#ifdef Q_QDOC
// Stop qdoc from complaining about missing function
~QPointer();
#endif
inline void

最低0.47元/天 解锁文章
4660

被折叠的 条评论
为什么被折叠?



