• Qt中无处不在的d指针为何方神圣


    在研究QCoreApplication类的代码时,无意间弄明白了“d_func()”和“d指针”的来源:

    class Q_CORE_EXPORT QCoreApplication
    #ifndef QT_NO_QOBJECT
    : public QObject
    #endif
    {
    ……
    Q_DECLARE_PRIVATE(QCoreApplication)
    public:
    ……
    ~QCoreApplication();
    ……
    protected:
    QCoreApplication(QCoreApplicationPrivate &p);

    #ifdef QT_NO_QOBJECT
    QScopedPointer<QCoreApplicationPrivate> d_ptr;
    #endif
    };
    上面的代码中出现了一个红“Q_DECLARE_PRIVATE”,接下来看看这个宏的作用。

    template <typename T> static inline T *qGetPtrHelper(T *ptr) { return ptr; }
    template <typename Wrapper> static inline typename Wrapper::pointer
    qGetPtrHelper(const Wrapper &p) { return p.data(); }
    #define Q_DECLARE_PRIVATE(Class)
    inline Class##Private* d_func() { return reinterpret_cast<Class##Private *>(qGetPtrHelper(d_ptr)); }
    inline const Class##Private* d_func() const { return reinterpret_cast<const Class##Private *>(qGetPtrHelper(d_ptr)); }
    friend class Class##Private;
    发现这个展开后引入了d_func()这个函数。但是“d指针”和这个宏又有什么关系呢?那就要说到另一个宏“Q_D”看如下的代码

    #define Q_D(Class) Class##Private * const d = d_func()
    从代码中可知,d_func()和d指针是紧密联系的。在Qt源码中“d_func()函数”和“d指针”的使用无处不在!
    在接下的过程中又发现了另一组宏“Q_DECLARE_PUBLIC、Q_Q”,代码如下:

    #define Q_DECLARE_PUBLIC(Class)
    inline Class* q_func() { return static_cast<Class *>(q_ptr); }
    inline const Class* q_func() const { return static_cast<const Class *>(q_ptr); }
    friend class Class;

    #define Q_Q(Class) Class * const q = q_func()
    这组宏引入了“q_func()函数”和“q指针”,这两个在Qt代码中遇见较少,留待以后研究。

    http://qtdream.com/topic/257/qt%E4%B8%AD%E6%97%A0%E5%A4%84%E4%B8%8D%E5%9C%A8%E7%9A%84d%E6%8C%87%E9%92%88%E4%B8%BA%E4%BD%95%E6%96%B9%E7%A5%9E%E5%9C%A3/4

    -------------------------------------------------------------------------------

     这个是pimpl模式,Qt广泛使用。简而言之,就是不让你知道这个类的私有成员是怎样的,有利于信息的隐藏以及高低版本的兼容。

    可以看看这两篇博文
    http://blog.csdn.net/mznewfacer/article/details/6976293
    http://blog.csdn.net/zhu_xz/article/details/6035861

  • 相关阅读:
    -bash: fork: Cannot allocate memory 问题的处理
    Docker top 命令
    docker常见问题修复方法
    The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
    What's the difference between encoding and charset?
    hexcode of é î Latin-1 Supplement
    炉石Advanced rulebook
    炉石bug反馈
    Sidecar pattern
    SQL JOIN
  • 原文地址:https://www.cnblogs.com/findumars/p/5313418.html
Copyright © 2020-2023  润新知