Search code examples
c++qtpimpl-idiom

What are the pros and cons of using d-pointers?


d-pointers are heavily used in Qt, they are an implementation of pimpl idiom. I know advantages and disadvantages of pimpl idiom. But I have missed the advantages of d-pointers implementation. Here and here are the samples of d-pointers. Isn't it easier to just use this?

class MyClassPrivate;
class MyClass {
  // interface methods
private:
  MyClassPrivate *pimpl_;
};

Solution

  • The set of macros for d-pointer pattern provides some sort convenience and consistencies. For example, Q_DECLARE_PRIVATE ensures that the pimpl private class for Foo is named as FooPrivate, that FooPrivate befriends Foo, and creates an nice inline function (both const and nonconst versions) called d_func(). The latter is used in Q_D macro, which basically creates a scoped/local variable d which points to the private class instance.

    In short, you need not use Q_DECLARE_PRIVATE and other macros, but doing so will make the code shorter, cleaner, and consistent.