D-Pointer: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
No edit summary
Line 1: Line 1:
'''English''' [[Dpointer SimplifiedChinese|简体中文]] [[Dpointer Ukrainian|Українська]] [[Dpointer Bulgarian|Български]] [[Dpointer Spanish|Español]] [[Dpointer Persian|فارسی]]
'''English''' [[Dpointer_SimplifiedChinese|简体中文]] [[Dpointer_Ukrainian|Українська]] [[Dpointer_Bulgarian|Български]] [[Dpointer_Spanish|Español]] [[Dpointer_Persian|فارسی]]<br />[[Category:Howto]]<br />[[Category:Developing with Qt]]<br />[[Category:QtInternals]]<br />[toc align_right=&quot;yes&amp;quot; depth=&quot;3&amp;quot;]


=What is the d-pointer=
= What is the d-pointer =


If you have looked into Qt source files like [http://qt.gitorious.org/qt/qt/blobs/HEAD/src/gui/widgets/qlabel.cpp this one] ''[qt.gitorious.org]'', you will find it generously sprinkled with <code>Q_D</code> and <code>Q_Q</code> macros. This article unravels the purpose of these macros.
If you have looked into Qt source files like &quot;this one&amp;quot;:http://qt.gitorious.org/qt/qt/blobs/HEAD/src/gui/widgets/qlabel.cpp, you will find it generously sprinkled with &lt;code&amp;gt;Q_D&amp;lt;/code&amp;gt; and &lt;code&amp;gt;Q_Q&amp;lt;/code&amp;gt; macros. This article unravels the purpose of these macros.


The <code>Q_D</code> and <code>Q_Q</code> macros are part of a design pattern called the d-pointer (also called the [http://en.wikipedia.org/wiki/Opaque_pointer opaque pointer] ''[en.wikipedia.org]'') where the implementation details of a library may be hidden from its users and changes to the implementation can be made to a library without breaking binary compatibility.
The &lt;code&amp;gt;Q_D&amp;lt;/code&amp;gt; and &lt;code&amp;gt;Q_Q&amp;lt;/code&amp;gt; macros are part of a design pattern called the d-pointer (also called the &quot;opaque pointer&amp;quot;:http://en.wikipedia.org/wiki/Opaque_pointer) where the implementation details of a library may be hidden from its users and changes to the implementation can be made to a library without breaking binary compatibility.


==Binary compatibility, what is that?==
== Binary compatibility, what is that? ==


When designing libraries like Qt, it is desirable that applications that dynamically link to Qt continue to run without recompiling even after the Qt library is upgraded/replaced with another version. For example, if your application ''CuteApp'' was based on Qt 4.5, you should be able to upgrade the Qt libraries (on Windows shipped with the application, on Linux often comes from package manager automatically!) from version 4.5 to Qt 4.6 and your CuteApp that was built with Qt 4.5 should still be able to run.
When designing libraries like Qt, it is desirable that applications that dynamically link to Qt continue to run without recompiling even after the Qt library is upgraded/replaced with another version. For example, if your application ''CuteApp'' was based on Qt 4.5, you should be able to upgrade the Qt libraries (on Windows shipped with the application, on Linux often comes from package manager automatically!) from version 4.5 to Qt 4.6 and your CuteApp that was built with Qt 4.5 should still be able to run.


===What breaks binary compatibility===
=== What breaks binary compatibility ===


So, when does a change in the library require a recompilation of the application? Let’s take a simple example:<br />
So, when does a change in the library require a recompilation of the application? Let's take a simple example:<br /><code><br /> class Widget {<br /> …<br /> private:<br /> Rect m_geometry;<br /> };
 
class Label : public Widget {<br /> public:<br /> …<br /> String text() const { return m_text; }<br /> private:<br /> String m_text;<br /> };<br /></code>


Here we have a Widget that contains geometry as a member variable. We compile our Widget and ship it as '''WidgetLib 1.0'''.
Here we have a Widget that contains geometry as a member variable. We compile our Widget and ship it as '''WidgetLib 1.0'''.


For '''WidgetLib 1.1''', someone comes up with the bright idea to add support for stylesheets. No sweat, we just add new methods and add a new ''data member''.<br />
For '''WidgetLib 1.1''', someone comes up with the bright idea to add support for stylesheets. No sweat, we just add new methods and add a new ''data member''.<br /><code><br /> class Widget {<br /> …<br /> private:<br /> Rect m_geometry;<br /> String m_stylesheet; // NEW in WidgetLib 1.1<br /> };
 
class Label : public Widget {<br /> public:<br /> …<br /> String text() const { return m_text; }<br /> private:<br /> String m_text;<br /> };<br /></code>


We ship WidgetLib 1.1 with the above change only to find that CuteApp that was compiled and ran just fine with WidgetLib 1.0 crashes gloriously!
We ship WidgetLib 1.1 with the above change only to find that CuteApp that was compiled and ran just fine with WidgetLib 1.0 crashes gloriously!


===Why did it crash?===
=== Why did it crash? ===


The reason is that by adding a new data member, we ended up changing the size of Widget and Label objects. Why does this matter? When your C++ compiler generates code, it uses ‘offsets’ to access data within an object.
The reason is that by adding a new data member, we ended up changing the size of Widget and Label objects. Why does this matter? When your C++ compiler generates code, it uses 'offsets' to access data within an object.


Here’s an oversimplified version of how the above <span class="caps">POD</span> objects might look in memory.
Here's an oversimplified version of how the above POD objects might look in memory.


{| class="infotable line"
{|
| '''Label object layout in WidgetLib 1.0'''
|'''Label object layout in WidgetLib 1.0'''
| '''Label object layout in WidgetLib 1.1'''
|'''Label object layout in WidgetLib 1.1'''
|-
|-
| m_geometry &lt;offset 0&gt;
|m_geometry &lt;offset 0&amp;gt;
| m_geometry &lt;offset 0&gt;
|m_geometry &lt;offset 0&amp;gt;
|-
|-
| ———————
|—————
| m_stylesheet &lt;offset 1&gt;
|m_stylesheet &lt;offset 1&amp;gt;
|-
|-
| m_text &lt;offset 1&gt;
|m_text &lt;offset 1&amp;gt;
| ————————-
|——————
|-
|-
| ———————-
|—————
| m_text &lt;offset 2&gt;
|m_text &lt;offset 2&amp;gt;
|}
|}


In WidgetLib 1.0, the text member of Label was at (logical) offset 1. The code generated by the compiler in the application for the method <code>Label::text()</code> translates to accessing offset 1 of the label object in the application. In WidgetLib 1.1, the ‘‘text’‘ member of Label has shifted to (logical) offset 2! Since the application has not been recompiled, it continues to think that <code>text</code> is at offset 1 and ends up accessing the<br /><code>stylesheet</code> variable!
In WidgetLib 1.0, the text member of Label was at (logical) offset 1. The code generated by the compiler in the application for the method &lt;code&amp;gt;Label::text()&lt;/code&amp;gt; translates to accessing offset 1 of the label object in the application. In WidgetLib 1.1, the ''text'' member of Label has shifted to (logical) offset 2! Since the application has not been recompiled, it continues to think that &lt;code&amp;gt;text&amp;lt;/code&amp;gt; is at offset 1 and ends up accessing the<br />&lt;code&amp;gt;stylesheet&amp;lt;/code&amp;gt; variable!


I am sure at this point there are a few who are wondering why the <code>Label::text()</code>‘s offset calculation code ended up in the CuteApp binary and not in the WidgetLib binary. The answer is that the code for <code>Label::text()</code> was defined in the header file and the compiler ended up [http://en.wikipedia.org/wiki/Inline_function inlining] ''[en.wikipedia.org]'' it.
I am sure at this point there are a few who are wondering why the &lt;code&amp;gt;Label::text()&lt;/code&amp;gt;'s offset calculation code ended up in the CuteApp binary and not in the WidgetLib binary. The answer is that the code for &lt;code&amp;gt;Label::text()&lt;/code&amp;gt; was defined in the header file and the compiler ended up &quot;inlining&amp;quot;:http://en.wikipedia.org/wiki/Inline_function it.


So, does the situation change if <code>Label::text()</code> had not been inlined? Say, <code>Label::text()</code> was moved to the source file? Well, no. The C++ compiler relies on the size of objects being the same at compile time and run-time. For example, stack winding/unwinding if you created a Label object on the stack, the compiler generated code to allocate space on the stack based on the Label’s size at compile time. Since the size of Label is different at run time in WidgetLib 1.1, Label’s constructor overwrites existing stack data and ends up corrupting the stack.
So, does the situation change if &lt;code&amp;gt;Label::text()&lt;/code&amp;gt; had not been inlined? Say, &lt;code&amp;gt;Label::text()&lt;/code&amp;gt; was moved to the source file? Well, no. The C++ compiler relies on the size of objects being the same at compile time and run-time. For example, stack winding/unwinding - if you created a Label object on the stack, the compiler generated code to allocate space on the stack based on the Label's size at compile time. Since the size of Label is different at run time in WidgetLib 1.1, Label's constructor overwrites existing stack data and ends up corrupting the stack.


===Never change the size of an exported C++ class===
=== Never change the size of an exported C++ class ===


In summary, never ever change the size or layout (don’t move the data around) of ''exported'' (i.e visible to the user) C++ classes once your library has been released. A C++ compiler generates code assuming that the size or the ordering of data in a class does not change ''after'' the application has been compiled.
In summary, never ever change the size or layout (don't move the data around) of ''exported'' (i.e visible to the user) C++ classes once your library has been released. A C++ compiler generates code assuming that the size or the ordering of data in a class does not change ''after'' the application has been compiled.


So, how can one not change the size of the object and yet add new features?
So, how can one not change the size of the object and yet add new features?


==The d-pointer==
== The d-pointer ==


The trick is to keep the size of all public classes of a library constant by only storing a single pointer. This pointer points to a private/internal data structure that contains all the data. The size of this internal structure can shrink or grow without having any side-effect on the application because the pointer is accessed only in the library code and from the application’s point of view the size of the object never changes – it’s always the size of the pointer. This pointer is called the ''d-pointer''.
The trick is to keep the size of all public classes of a library constant by only storing a single pointer. This pointer points to a private/internal data structure that contains all the data. The size of this internal structure can shrink or grow without having any side-effect on the application because the pointer is accessed only in the library code and from the application's point of view the size of the object never changes - it's always the size of the pointer. This pointer is called the ''d-pointer''.


The spirit of this pattern is outlined in the code below (all code in this article doesn’t have destructors, of course you should add them in real code).
The spirit of this pattern is outlined in the code below (all code in this article doesn't have destructors, of course you should add them in real code).


'''widget.h'''<br />
'''widget.h'''<br /><code><br /> /* Since d_ptr is a pointer and is never referended in header file<br /> &amp;#40;it would cause a compile error&amp;amp;#41; WidgetPrivate doesn't have to be included,<br /> but forward-declared instead.<br /> The definition of the class can be written in widget.cpp or<br /> in a separate file, say widget_p.h*/


'''widget_p.h''', which is the private header file of the widget class<br />
class WidgetPrivate;


'''widget.cpp'''<br />
class Widget {<br /> …<br /> Rect geometry() const;<br /> …<br /> private:<br /> WidgetPrivate *d_ptr;<br /> };<br /></code>


Next, there’s an example of a child class based on Widget.
'''widget_p.h''', which is the private header file of the widget class<br /><code><br /> /* widget_p.h (_p means private) */<br /> struct WidgetPrivate {<br /> Rect geometry;<br /> String stylesheet;<br /> };<br /></code>


'''label.h'''<br />
'''widget.cpp'''<br /><code><br /> // With this #include, we can access WidgetPrivate.<br /> #include &quot;widget_p.h&amp;quot;<br /> Widget::Widget()<br /> : d_ptr(new WidgetPrivate) {<br /> // Creation of private data<br /> }


'''label.cpp'''<br />
Rect Widget::geometry() const {<br /> // The d-ptr is only accessed in the library code<br /> return d_ptr-&gt;geometry;<br /> }<br /></code>
 
Next, there's an example of a child class based on Widget.
 
'''label.h'''<br /><code><br /> class Label : public Widget {<br /> …<br /> String text();<br /> private:<br /> // Each class maintains its own d-pointer<br /> LabelPrivate *d_ptr;<br /> };<br /></code>
 
'''label.cpp'''<br /><code><br /> // Unlike WidgetPrivate, the author decided LabelPrivate to be defined in the source file itself<br /> struct LabelPrivate {<br /> String text;<br /> };
 
Label::Label()<br /> : d_ptr(new LabelPrivate) {<br /> }
 
String Label::text() {<br /> return d_ptr-&gt;text;<br /> }<br /></code>


With the above structure, CuteApp never accesses the d-pointer directly. And since the ''d-pointer'' is only ever accessed in WidgetLib and WidgetLib is recompiled for every release, the Private class can freely change with no impact on CuteApp.
With the above structure, CuteApp never accesses the d-pointer directly. And since the ''d-pointer'' is only ever accessed in WidgetLib and WidgetLib is recompiled for every release, the Private class can freely change with no impact on CuteApp.


===Other benefits of d-pointer===
=== Other benefits of d-pointer ===
 
It's not all about binary compatibility. The d-pointer has other benefits:<br />* Hide implementation details - We can ship WidgetLib with just the header files and the binaries. The .cpp files can be closed source.<br />* The header file is clean of implementation details and can serve as the API reference.<br />* Since the header files needed for implementation are moved from the header file into the implementation (source) file, compiles are much faster.


It’s not all about binary compatibility. The d-pointer has other benefits:
It is indeed true that the above benefits appear trivial. The real reason to use d-pointers in Qt is for binary compatibility and the fact that Qt started out closed source.


* Hide implementation details – We can ship WidgetLib with just the header files and the binaries. The .cpp files can be closed source.
== The q-pointer ==
* The header file is clean of implementation details and can serve as the <span class="caps">API</span> reference.
* Since the header files needed for implementation are moved from the header file into the implementation (source) file, compiles are much faster.


It is indeed true that the above benefits appear trivial. The real reason to use d-pointers in Qt is for binary compatibility and the fact that Qt started out closed source.
So far, we have only seen the d-pointer as a C-style data structure. In reality, it contains private methods (helper functions). For example, &lt;code&amp;gt;LabelPrivate&amp;lt;/code&amp;gt; might have a &lt;code&amp;gt;getLinkTargetFromPoint()&lt;/code&amp;gt; helper function that is required to find the link target when the mouse is clicked. In many cases, these helper methods require access to the public class i.e some functions from Label or from its base class Widget. For example, a helper method, &lt;code&amp;gt;setTextAndUpdateWidget()&lt;/code&amp;gt; might want to call &lt;code&amp;gt;Widget::update()&lt;/code&amp;gt; which is a public method to schedule a redraw the Widget. So, the &lt;code&amp;gt;WidgetPrivate&amp;lt;/code&amp;gt; stores a pointer to the public class called the q-pointer. Modifying the code above for the q-pointer, we get:


==The q-pointer==
'''widget.h'''<br /><code><br /> class WidgetPrivate;


So far, we have only seen the d-pointer as a C-style data structure. In reality, it contains private methods (helper functions). For example, <code>LabelPrivate</code> might have a <code>getLinkTargetFromPoint()</code> helper function that is required to find the link target when the mouse is clicked. In many cases, these helper methods require access to the public class i.e some functions from Label or from its base class Widget. For example, a helper method, <code>setTextAndUpdateWidget()</code> might want to call <code>Widget::update()</code> which is a public method to schedule a redraw the Widget. So, the <code>WidgetPrivate</code> stores a pointer to the public class called the q-pointer. Modifying the code above for the q-pointer, we get:
class Widget {<br /> <br /> Rect geometry() const;<br /> <br /> private:<br /> WidgetPrivate *d_ptr;<br /> };<br /></code>


'''widget.h'''
'''widget_p.h'''<br /><code><br /> struct WidgetPrivate {<br /> // Constructor that initializes the q-ptr<br /> WidgetPrivate(Widget *q) : q_ptr(q) { }<br /> Widget *q_ptr; // q-ptr points to the API class<br /> Rect geometry;<br /> String stylesheet;<br /> };<br /></code>


'''widget_p.h'''<br />
'''widget.cpp'''<br /><code><br /> #include &quot;widget_p.h&amp;quot;<br /> // Create private data.<br /> // Pass the 'this' pointer to initialize the q-ptr<br /> Widget::Widget()<br /> : d_ptr(new WidgetPrivate(this)) {<br /> }


'''widget.cpp'''<br />
Rect Widget::geometry() const {<br /> // the d-ptr is only accessed in the library code<br /> return d_ptr-&gt;geometry;<br /> }<br /></code>


Next, another class based on Widget.
Next, another class based on Widget.


'''label.h'''<br />
'''label.h'''<br /><code><br /> class Label : public Widget {<br /> …<br /> String text() const;<br /> private:<br /> LabelPrivate *d_ptr;<br /> };<br /></code>
 
'''label.cpp'''<br /><code><br /> // Unlike WidgetPrivate, the author decided LabelPrivate to be defined in the source file itself<br /> struct LabelPrivate {<br /> LabelPrivate(Label *q) : q_ptr(q) { }<br /> Label *q_ptr;<br /> String text;<br /> };
 
Label::Label()<br /> : d_ptr(new LabelPrivate(this)) {<br /> }


'''label.cpp'''<br />
String Label::text() {<br /> return d_ptr-&gt;text;<br /> }<br /></code>


==Inheriting d-pointers for optimization==
== Inheriting d-pointers for optimization ==


In the above code, creating a single Label results in the memory allocation for <code>LabelPrivate</code> and <code>WidgetPrivate</code>. If we were to employ this strategy for Qt, the situation becomes quite worse for classes like <code>QListWidget</code> – it is 6 levels deep in the class inheritance hierarchy and it would result in upto 6 memory allocations!
In the above code, creating a single Label results in the memory allocation for &lt;code&amp;gt;LabelPrivate&amp;lt;/code&amp;gt; and &lt;code&amp;gt;WidgetPrivate&amp;lt;/code&amp;gt;. If we were to employ this strategy for Qt, the situation becomes quite worse for classes like &lt;code&amp;gt;QListWidget&amp;lt;/code&amp;gt; - it is 6 levels deep in the class inheritance hierarchy and it would result in upto 6 memory allocations!


This is solved by having an inheritance hierarchy for our ''private'' classes and having the class getting instantiated pass on a the d-pointer all the way up.
This is solved by having an inheritance hierarchy for our ''private'' classes and having the class getting instantiated pass on a the d-pointer all the way up.


Notice that when inheriting d-pointers, the declaration of the private class has to be in a separate file, for example widget_p.h. It’s no longer possible to declare it in the widget.cpp file.
Notice that when inheriting d-pointers, the declaration of the private class has to be in a separate file, for example widget_p.h. It's no longer possible to declare it in the widget.cpp file.
 
'''widget.h'''<br /><code><br /> class Widget {<br /> public:<br /> Widget();<br /> …<br /> protected:<br /> // only sublasses may access the below<br /> Widget(WidgetPrivate &amp;d); // allow subclasses to initialize with their own concrete Private<br /> WidgetPrivate *d_ptr;<br /> };<br /></code>
 
'''widget_p.h'''<br /><code><br /> struct WidgetPrivate {<br /> WidgetPrivate(Widget *q) : q_ptr(q) { } // constructor that initializes the q-ptr<br /> Widget *q_ptr; // q-ptr that points to the API class<br /> Rect geometry;<br /> String stylesheet;<br /> };<br /></code>
 
'''widget.cpp'''<br /><code><br /> Widget::Widget()<br /> : d_ptr(new WidgetPrivate(this)) {<br /> }


'''widget.h'''<br />
Widget::Widget(WidgetPrivate &amp;d)<br /> : d_ptr(&amp;d) {<br /> }<br /></code>


'''widget_p.h'''<br />
'''label.h'''<br /><code><br /> class Label : public Widget {<br /> public:<br /> Label();<br /> …<br /> protected:<br /> Label(LabelPrivate &amp;d); // allow Label subclasses to pass on their Private<br /> // notice how Label does not have a d_ptr! It just uses Widget's d_ptr.<br /> };<br /></code>


'''widget.cpp'''<br />
'''label.cpp'''<br /><code><br /> #include &quot;widget_p.h&amp;quot;


'''label.h'''<br />
class LabelPrivate : public WidgetPrivate {<br /> public:<br /> String text;<br /> };


'''label.cpp'''<br />
Label::Label()<br /> : Widget(*new LabelPrivate) // initialize the d-pointer with our own Private {<br /> }


Do you see the beauty? When we now create a <code>Label</code> object, it will create a <code>LabelPrivate</code> (which subclasses <code>WidgetPrivate</code>). It passes on the concrete ''d-pointer'' to Widget’s protected constructor! Now, when a <code>Label</code> object is created, there is only one memory allocation. Label also has a protected constructor that can be used by its subclasses to provide their own private classes.
Label::Label(LabelPrivate &amp;d)<br /> : Widget(d) {<br /> }<br /></code>


==d-pointers in Qt==
Do you see the beauty? When we now create a &lt;code&amp;gt;Label&amp;lt;/code&amp;gt; object, it will create a &lt;code&amp;gt;LabelPrivate&amp;lt;/code&amp;gt; (which subclasses &lt;code&amp;gt;WidgetPrivate&amp;lt;/code&amp;gt;). It passes on the concrete ''d-pointer'' to Widget's protected constructor! Now, when a &lt;code&amp;gt;Label&amp;lt;/code&amp;gt; object is created, there is only one memory allocation. Label also has a protected constructor that can be used by its subclasses to provide their own private classes.


In Qt, practically every public class uses the d-pointer approach. The only cases where it’s not used is when it is known in advance that the class will never ever have extra member variables added to it. For example, for classes like <code>QPoint</code>, <code>QRect</code>, no new members are expected to be added and hence the data members are stored straight into the class itself instead of using the d-pointer.
== d-pointers in Qt ==


Notice that in Qt, the base class of all Private objects is <code>QObjectPrivate</code>.
In Qt, practically every public class uses the d-pointer approach. The only cases where it's not used is when it is known in advance that the class will never ever have extra member variables added to it. For example, for classes like &lt;code&amp;gt;QPoint&amp;lt;/code&amp;gt;, &lt;code&amp;gt;QRect&amp;lt;/code&amp;gt;, no new members are expected to be added and hence the data members are stored straight into the class itself instead of using the d-pointer.


===Q_D and Q_Q===
Notice that in Qt, the base class of all Private objects is &lt;code&amp;gt;QObjectPrivate&amp;lt;/code&amp;gt;.


A side effect of the optimization that we did in the previous step is that the q-ptr and d-ptr are of type <code>Widget</code> and <code>WidgetPrivate</code>. This means that the following won’t work.
=== Q_D and Q_Q ===


Hence, when accessing the d-pointer in a subclass, we need to static_cast to the appropriate type.<br />
A side effect of the optimization that we did in the previous step is that the q-ptr and d-ptr are of type &lt;code&amp;gt;Widget&amp;lt;/code&amp;gt; and &lt;code&amp;gt;WidgetPrivate&amp;lt;/code&amp;gt;. This means that the following won't work.


As you can see, it’s not pretty having static_cast all over the place. Instead, there are two macros defined in src/corelib/global/qglobal.h which make it straighforward:
<code><br /> void Label::setText(const String &amp;text) {<br /> // won't work! since d_ptr is of type WidgetPrivate even though it points to LabelPrivate object<br /> d_ptr-&gt;text = text;<br /> }<br /></code>


'''global.h'''<br />
Hence, when accessing the d-pointer in a subclass, we need to static_cast to the appropriate type.<br /><code><br /> void Label::setText(const String &amp;text) {<br /> LabelPrivate '''d = static_cast&amp;lt;LabelPrivate'''&gt;(d_ptr); // cast to our private type<br /> d-&gt;text = text;<br /> }<br /></code>


'''label.cpp'''<br />
As you can see, it's not pretty having static_cast all over the place. Instead, there are two macros defined in src/corelib/global/qglobal.h which make it straighforward:


===Q_DECLARE_PRIVATE and Q_DECLARE_PUBLIC===
'''global.h'''<br /><code><br /> #define Q_D(Class) Class##Private * const d = d_func()<br /> #define Q_Q(Class) Class * const q = q_func()<br /></code>


Qt classes have a <code>Q_DECLARE_PRIVATE</code> a macro in the public class. The macro reads:
'''label.cpp'''<br /><code><br />//With Q_D you can use the members of LabelPrivate from Label<br /> void Label::setText(const String &amp;text) {<br /> Q_D(Label);<br /> d-&gt;text = text;<br /> }<br />//With Q_Q you can use the members of Label from LabelPrivate<br /> void LabelPrivate::someHelperFunction() {<br /> Q_Q(Label);<br /> q-&gt;selectAll();<br /> }<br /></code>


'''qglobal.h'''<br />
=== Q_DECLARE_PRIVATE and Q_DECLARE_PUBLIC ===


This macro can be used this way:
Qt classes have a &lt;code&amp;gt;Q_DECLARE_PRIVATE&amp;lt;/code&amp;gt; a macro in the public class. The macro reads:


'''qlabel.h'''<br /> The idea is that <code>QLabel</code> provides a function <code>d_func()</code> that allows access to its private internal class. The method itself is private (since the macro is inside a private section in qlabel.h). The <code>d_func()</code> can however be invoked by '''friends''' (C++ friend) of <code>QLabel</code>. This is primarily useful for access of information by Qt classes which cannot get access of some <code>QLabel</code> information using public api. As a bizarre example, <code>QLabel</code> might keep track of how many times the user has clicked on a link. However, there is no public <span class="caps">API</span> to access this information. <code>QStatistics</code> is a class that needs this information. A Qt developer will add <code>QStatistics</code> as a friend of <code>QLabel</code> and <code>QStatistics</code> can then do <code>label-&gt;d_func()-&gt;linkClickCount</code>.
'''qglobal.h'''<br /><code><br /> #define Q_DECLARE_PRIVATE(Class) inline Class##Private* d_func() { return reinterpret_cast&amp;lt;Class##Private '''&gt;(qGetPtrHelper(d_ptr)); }  inline const Class##Private''' d_func() const {  return reinterpret_cast&amp;lt;const Class##Private *&gt;(qGetPtrHelper(d_ptr)); }  friend class Class##Private;<br /></code>


The <code>d_func</code> also has the advantage to enforce const-correctness: In a const member function of MyClass you need a Q_D(const MyClass) and thus you can only call const member functions in MyClassPrivate. With a “naked” d_ptr you could also call non-const functions.
This macro can be used this way:


There’s also a <code>Q_DECLARE_PUBLIC</code> which goes the other way round.
'''qlabel.h'''<br /><code><br /> class QLabel {<br /> private:<br /> Q_DECLARE_PRIVATE(QLabel);<br /> };<br /></code>


===Categories:===
The idea is that &lt;code&amp;gt;QLabel&amp;lt;/code&amp;gt; provides a function &lt;code&amp;gt;d_func()&lt;/code&amp;gt; that allows access to its private internal class. The method itself is private (since the macro is inside a private section in qlabel.h). The &lt;code&amp;gt;d_func()&lt;/code&amp;gt; can however be invoked by '''friends''' (C++ friend) of &lt;code&amp;gt;QLabel&amp;lt;/code&amp;gt;. This is primarily useful for access of information by Qt classes which cannot get access of some &lt;code&amp;gt;QLabel&amp;lt;/code&amp;gt; information using public api. As a bizarre example, &lt;code&amp;gt;QLabel&amp;lt;/code&amp;gt; might keep track of how many times the user has clicked on a link. However, there is no public API to access this information. &lt;code&amp;gt;QStatistics&amp;lt;/code&amp;gt; is a class that needs this information. A Qt developer will add &lt;code&amp;gt;QStatistics&amp;lt;/code&amp;gt; as a friend of &lt;code&amp;gt;QLabel&amp;lt;/code&amp;gt; and &lt;code&amp;gt;QStatistics&amp;lt;/code&amp;gt; can then do &lt;code&amp;gt;label-&gt;d_func()-&gt;linkClickCount&amp;lt;/code&amp;gt;.


* [[:Category:Developing-with-Qt|Developing with Qt]]
The &lt;code&amp;gt;d_func&amp;lt;/code&amp;gt; also has the advantage to enforce const-correctness: In a const member function of MyClass you need a Q_D(const MyClass) and thus you can only call const member functions in MyClassPrivate. With a &quot;naked&amp;quot; d_ptr you could also call non-const functions.
* [[:Category:HowTo|HowTo]]
* [[:Category:QtInternals|QtInternals]]

Revision as of 14:18, 23 February 2015

English 简体中文 Українська Български Español فارسی



[toc align_right="yes&quot; depth="3&quot;]

What is the d-pointer

If you have looked into Qt source files like "this one&quot;:http://qt.gitorious.org/qt/qt/blobs/HEAD/src/gui/widgets/qlabel.cpp, you will find it generously sprinkled with <code&gt;Q_D&lt;/code&gt; and <code&gt;Q_Q&lt;/code&gt; macros. This article unravels the purpose of these macros.

The <code&gt;Q_D&lt;/code&gt; and <code&gt;Q_Q&lt;/code&gt; macros are part of a design pattern called the d-pointer (also called the "opaque pointer&quot;:http://en.wikipedia.org/wiki/Opaque_pointer) where the implementation details of a library may be hidden from its users and changes to the implementation can be made to a library without breaking binary compatibility.

Binary compatibility, what is that?

When designing libraries like Qt, it is desirable that applications that dynamically link to Qt continue to run without recompiling even after the Qt library is upgraded/replaced with another version. For example, if your application CuteApp was based on Qt 4.5, you should be able to upgrade the Qt libraries (on Windows shipped with the application, on Linux often comes from package manager automatically!) from version 4.5 to Qt 4.6 and your CuteApp that was built with Qt 4.5 should still be able to run.

What breaks binary compatibility

So, when does a change in the library require a recompilation of the application? Let's take a simple example:

<br /> class Widget {<br /> <br /> private:<br /> Rect m_geometry;<br /> };

class Label : public Widget {<br /> public:<br /> <br /> String text() const { return m_text; }<br /> private:<br /> String m_text;<br /> };<br />

Here we have a Widget that contains geometry as a member variable. We compile our Widget and ship it as WidgetLib 1.0.

For WidgetLib 1.1, someone comes up with the bright idea to add support for stylesheets. No sweat, we just add new methods and add a new data member.

<br /> class Widget {<br /> <br /> private:<br /> Rect m_geometry;<br /> String m_stylesheet; // NEW in WidgetLib 1.1<br /> };

class Label : public Widget {<br /> public:<br /> <br /> String text() const { return m_text; }<br /> private:<br /> String m_text;<br /> };<br />

We ship WidgetLib 1.1 with the above change only to find that CuteApp that was compiled and ran just fine with WidgetLib 1.0 crashes gloriously!

Why did it crash?

The reason is that by adding a new data member, we ended up changing the size of Widget and Label objects. Why does this matter? When your C++ compiler generates code, it uses 'offsets' to access data within an object.

Here's an oversimplified version of how the above POD objects might look in memory.

Label object layout in WidgetLib 1.0 Label object layout in WidgetLib 1.1
m_geometry <offset 0&gt; m_geometry <offset 0&gt;
————— m_stylesheet <offset 1&gt;
m_text <offset 1&gt; ——————
————— m_text <offset 2&gt;

In WidgetLib 1.0, the text member of Label was at (logical) offset 1. The code generated by the compiler in the application for the method <code&gt;Label::text()</code&gt; translates to accessing offset 1 of the label object in the application. In WidgetLib 1.1, the text member of Label has shifted to (logical) offset 2! Since the application has not been recompiled, it continues to think that <code&gt;text&lt;/code&gt; is at offset 1 and ends up accessing the
<code&gt;stylesheet&lt;/code&gt; variable!

I am sure at this point there are a few who are wondering why the <code&gt;Label::text()</code&gt;'s offset calculation code ended up in the CuteApp binary and not in the WidgetLib binary. The answer is that the code for <code&gt;Label::text()</code&gt; was defined in the header file and the compiler ended up "inlining&quot;:http://en.wikipedia.org/wiki/Inline_function it.

So, does the situation change if <code&gt;Label::text()</code&gt; had not been inlined? Say, <code&gt;Label::text()</code&gt; was moved to the source file? Well, no. The C++ compiler relies on the size of objects being the same at compile time and run-time. For example, stack winding/unwinding - if you created a Label object on the stack, the compiler generated code to allocate space on the stack based on the Label's size at compile time. Since the size of Label is different at run time in WidgetLib 1.1, Label's constructor overwrites existing stack data and ends up corrupting the stack.

Never change the size of an exported C++ class

In summary, never ever change the size or layout (don't move the data around) of exported (i.e visible to the user) C++ classes once your library has been released. A C++ compiler generates code assuming that the size or the ordering of data in a class does not change after the application has been compiled.

So, how can one not change the size of the object and yet add new features?

The d-pointer

The trick is to keep the size of all public classes of a library constant by only storing a single pointer. This pointer points to a private/internal data structure that contains all the data. The size of this internal structure can shrink or grow without having any side-effect on the application because the pointer is accessed only in the library code and from the application's point of view the size of the object never changes - it's always the size of the pointer. This pointer is called the d-pointer.

The spirit of this pattern is outlined in the code below (all code in this article doesn't have destructors, of course you should add them in real code).

widget.h

<br /> /* Since d_ptr is a pointer and is never referended in header file<br /> &amp;#40;it would cause a compile error&amp;amp;#41; WidgetPrivate doesn't have to be included,<br /> but forward-declared instead.<br /> The definition of the class can be written in widget.cpp or<br /> in a separate file, say widget_p.h*/

class WidgetPrivate;

class Widget {<br /> <br /> Rect geometry() const;<br /> <br /> private:<br /> WidgetPrivate *d_ptr;<br /> };<br />

widget_p.h, which is the private header file of the widget class

<br /> /* widget_p.h (_p means private) */<br /> struct WidgetPrivate {<br /> Rect geometry;<br /> String stylesheet;<br /> };<br />

widget.cpp

<br /> // With this #include, we can access WidgetPrivate.<br /> #include &quot;widget_p.h&amp;quot;<br /> Widget::Widget()<br /> : d_ptr(new WidgetPrivate) {<br /> // Creation of private data<br /> }

Rect Widget::geometry() const {<br /> // The d-ptr is only accessed in the library code<br /> return d_ptr-&gt;geometry;<br /> }<br />

Next, there's an example of a child class based on Widget.

label.h

<br /> class Label : public Widget {<br /> <br /> String text();<br /> private:<br /> // Each class maintains its own d-pointer<br /> LabelPrivate *d_ptr;<br /> };<br />

label.cpp

<br /> // Unlike WidgetPrivate, the author decided LabelPrivate to be defined in the source file itself<br /> struct LabelPrivate {<br /> String text;<br /> };

Label::Label()<br /> : d_ptr(new LabelPrivate) {<br /> }

String Label::text() {<br /> return d_ptr-&gt;text;<br /> }<br />

With the above structure, CuteApp never accesses the d-pointer directly. And since the d-pointer is only ever accessed in WidgetLib and WidgetLib is recompiled for every release, the Private class can freely change with no impact on CuteApp.

Other benefits of d-pointer

It's not all about binary compatibility. The d-pointer has other benefits:
* Hide implementation details - We can ship WidgetLib with just the header files and the binaries. The .cpp files can be closed source.
* The header file is clean of implementation details and can serve as the API reference.
* Since the header files needed for implementation are moved from the header file into the implementation (source) file, compiles are much faster.

It is indeed true that the above benefits appear trivial. The real reason to use d-pointers in Qt is for binary compatibility and the fact that Qt started out closed source.

The q-pointer

So far, we have only seen the d-pointer as a C-style data structure. In reality, it contains private methods (helper functions). For example, <code&gt;LabelPrivate&lt;/code&gt; might have a <code&gt;getLinkTargetFromPoint()</code&gt; helper function that is required to find the link target when the mouse is clicked. In many cases, these helper methods require access to the public class i.e some functions from Label or from its base class Widget. For example, a helper method, <code&gt;setTextAndUpdateWidget()</code&gt; might want to call <code&gt;Widget::update()</code&gt; which is a public method to schedule a redraw the Widget. So, the <code&gt;WidgetPrivate&lt;/code&gt; stores a pointer to the public class called the q-pointer. Modifying the code above for the q-pointer, we get:

widget.h

<br /> class WidgetPrivate;

class Widget {<br /> <br /> Rect geometry() const;<br /> <br /> private:<br /> WidgetPrivate *d_ptr;<br /> };<br />

widget_p.h

<br /> struct WidgetPrivate {<br /> // Constructor that initializes the q-ptr<br /> WidgetPrivate(Widget *q) : q_ptr(q) { }<br /> Widget *q_ptr; // q-ptr points to the API class<br /> Rect geometry;<br /> String stylesheet;<br /> };<br />

widget.cpp

<br /> #include &quot;widget_p.h&amp;quot;<br /> // Create private data.<br /> // Pass the 'this' pointer to initialize the q-ptr<br /> Widget::Widget()<br /> : d_ptr(new WidgetPrivate(this)) {<br /> }

Rect Widget::geometry() const {<br /> // the d-ptr is only accessed in the library code<br /> return d_ptr-&gt;geometry;<br /> }<br />

Next, another class based on Widget.

label.h

<br /> class Label : public Widget {<br /> <br /> String text() const;<br /> private:<br /> LabelPrivate *d_ptr;<br /> };<br />

label.cpp

<br /> // Unlike WidgetPrivate, the author decided LabelPrivate to be defined in the source file itself<br /> struct LabelPrivate {<br /> LabelPrivate(Label *q) : q_ptr(q) { }<br /> Label *q_ptr;<br /> String text;<br /> };

Label::Label()<br /> : d_ptr(new LabelPrivate(this)) {<br /> }

String Label::text() {<br /> return d_ptr-&gt;text;<br /> }<br />

Inheriting d-pointers for optimization

In the above code, creating a single Label results in the memory allocation for <code&gt;LabelPrivate&lt;/code&gt; and <code&gt;WidgetPrivate&lt;/code&gt;. If we were to employ this strategy for Qt, the situation becomes quite worse for classes like <code&gt;QListWidget&lt;/code&gt; - it is 6 levels deep in the class inheritance hierarchy and it would result in upto 6 memory allocations!

This is solved by having an inheritance hierarchy for our private classes and having the class getting instantiated pass on a the d-pointer all the way up.

Notice that when inheriting d-pointers, the declaration of the private class has to be in a separate file, for example widget_p.h. It's no longer possible to declare it in the widget.cpp file.

widget.h

<br /> class Widget {<br /> public:<br /> Widget();<br /> <br /> protected:<br /> // only sublasses may access the below<br /> Widget(WidgetPrivate &amp;d); // allow subclasses to initialize with their own concrete Private<br /> WidgetPrivate *d_ptr;<br /> };<br />

widget_p.h

<br /> struct WidgetPrivate {<br /> WidgetPrivate(Widget *q) : q_ptr(q) { } // constructor that initializes the q-ptr<br /> Widget *q_ptr; // q-ptr that points to the API class<br /> Rect geometry;<br /> String stylesheet;<br /> };<br />

widget.cpp

<br /> Widget::Widget()<br /> : d_ptr(new WidgetPrivate(this)) {<br /> }

Widget::Widget(WidgetPrivate &amp;d)<br /> : d_ptr(&amp;d) {<br /> }<br />

label.h

<br /> class Label : public Widget {<br /> public:<br /> Label();<br /> <br /> protected:<br /> Label(LabelPrivate &amp;d); // allow Label subclasses to pass on their Private<br /> // notice how Label does not have a d_ptr! It just uses Widget's d_ptr.<br /> };<br />

label.cpp

<br /> #include &quot;widget_p.h&amp;quot;

class LabelPrivate : public WidgetPrivate {<br /> public:<br /> String text;<br /> };

Label::Label()<br /> : Widget(*new LabelPrivate) // initialize the d-pointer with our own Private {<br /> }

Label::Label(LabelPrivate &amp;d)<br /> : Widget(d) {<br /> }<br />

Do you see the beauty? When we now create a <code&gt;Label&lt;/code&gt; object, it will create a <code&gt;LabelPrivate&lt;/code&gt; (which subclasses <code&gt;WidgetPrivate&lt;/code&gt;). It passes on the concrete d-pointer to Widget's protected constructor! Now, when a <code&gt;Label&lt;/code&gt; object is created, there is only one memory allocation. Label also has a protected constructor that can be used by its subclasses to provide their own private classes.

d-pointers in Qt

In Qt, practically every public class uses the d-pointer approach. The only cases where it's not used is when it is known in advance that the class will never ever have extra member variables added to it. For example, for classes like <code&gt;QPoint&lt;/code&gt;, <code&gt;QRect&lt;/code&gt;, no new members are expected to be added and hence the data members are stored straight into the class itself instead of using the d-pointer.

Notice that in Qt, the base class of all Private objects is <code&gt;QObjectPrivate&lt;/code&gt;.

Q_D and Q_Q

A side effect of the optimization that we did in the previous step is that the q-ptr and d-ptr are of type <code&gt;Widget&lt;/code&gt; and <code&gt;WidgetPrivate&lt;/code&gt;. This means that the following won't work.

<br /> void Label::setText(const String &amp;text) {<br /> // won't work! since d_ptr is of type WidgetPrivate even though it points to LabelPrivate object<br /> d_ptr-&gt;text = text;<br /> }<br />

Hence, when accessing the d-pointer in a subclass, we need to static_cast to the appropriate type.

<br /> void Label::setText(const String &amp;text) {<br /> LabelPrivate '''d = static_cast&amp;lt;LabelPrivate'''&gt;(d_ptr); // cast to our private type<br /> d-&gt;text = text;<br /> }<br />

As you can see, it's not pretty having static_cast all over the place. Instead, there are two macros defined in src/corelib/global/qglobal.h which make it straighforward:

global.h

<br /> #define Q_D(Class) Class##Private * const d = d_func()<br /> #define Q_Q(Class) Class * const q = q_func()<br />

label.cpp

<br />//With Q_D you can use the members of LabelPrivate from Label<br /> void Label::setText(const String &amp;text) {<br /> Q_D(Label);<br /> d-&gt;text = text;<br /> }<br />//With Q_Q you can use the members of Label from LabelPrivate<br /> void LabelPrivate::someHelperFunction() {<br /> Q_Q(Label);<br /> q-&gt;selectAll();<br /> }<br />

Q_DECLARE_PRIVATE and Q_DECLARE_PUBLIC

Qt classes have a <code&gt;Q_DECLARE_PRIVATE&lt;/code&gt; a macro in the public class. The macro reads:

qglobal.h

<br /> #define Q_DECLARE_PRIVATE(Class)  inline Class##Private* d_func() { return reinterpret_cast&amp;lt;Class##Private '''&gt;(qGetPtrHelper(d_ptr)); }  inline const Class##Private''' d_func() const {  return reinterpret_cast&amp;lt;const Class##Private *&gt;(qGetPtrHelper(d_ptr)); }  friend class Class##Private;<br />

This macro can be used this way:

qlabel.h

<br /> class QLabel {<br /> private:<br /> Q_DECLARE_PRIVATE(QLabel);<br /> };<br />

The idea is that <code&gt;QLabel&lt;/code&gt; provides a function <code&gt;d_func()</code&gt; that allows access to its private internal class. The method itself is private (since the macro is inside a private section in qlabel.h). The <code&gt;d_func()</code&gt; can however be invoked by friends (C++ friend) of <code&gt;QLabel&lt;/code&gt;. This is primarily useful for access of information by Qt classes which cannot get access of some <code&gt;QLabel&lt;/code&gt; information using public api. As a bizarre example, <code&gt;QLabel&lt;/code&gt; might keep track of how many times the user has clicked on a link. However, there is no public API to access this information. <code&gt;QStatistics&lt;/code&gt; is a class that needs this information. A Qt developer will add <code&gt;QStatistics&lt;/code&gt; as a friend of <code&gt;QLabel&lt;/code&gt; and <code&gt;QStatistics&lt;/code&gt; can then do <code&gt;label->d_func()->linkClickCount&lt;/code&gt;.

The <code&gt;d_func&lt;/code&gt; also has the advantage to enforce const-correctness: In a const member function of MyClass you need a Q_D(const MyClass) and thus you can only call const member functions in MyClassPrivate. With a "naked&quot; d_ptr you could also call non-const functions.