<?xml version="1.0" encoding="UTF-8" ?><rss version="2.0"><channel><title>Woboq</title><description>Woboq does Qt consulting and services</description><link>http://woboq.com</link>

<item><title>Data initialization in C++</title><link>http://woboq.com/blog/data-and-initialisation.html</link><pubDate>Thu, 16 May 2013 19:12:07 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>
In this blog post, I am going to review the different kind of data and how they are initialized in a program.
</p>
</div>
<p>
What I am going to explain here is valid for Linux and GCC.
<!--But I suppose it is similar with different platform.-->
</p>
<h2>Code Example</h2>
<p>I'll just start by showing a small piece of code. What is going to interest us is where
the data will end up in memory and how it is initialized.</p>
<pre class="brush: cpp">
const char string_data[] = "hello world"; // .rodata
const int even_numbers[] = { 0*2 , 1*2,  2*2,  3*2, 4*2}; //.rodata

int all_numbers[] = { 0, 1, 2, 3, 4 };  //.data

static inline int odd(int n) { return n*2 + 1; }
const int odd_numbers[] = { odd(0), odd(1), odd(2), odd(3), odd(4) }; //initialized

QString qstring_data("hello QString"); //object with constructor and destructor

</pre>
<p>I'll analyze the assembly. It has been generated with the following command,
then re-formatted for better presentation in this blog post.</p>
<pre>
g++ -O2 -S data.cpp
</pre>
<p>(I also had to add a function that uses the data in order to avoid 
    that the compiler removes some arrays that were not used.)</p>
<h2>The sections</h2>
<p>On Linux, the binaries (program or libraries) are stored as file in the 
<a href="http://en.wikipedia.org/wiki/Executable_and_Linkable_Format">ELF format</a>.
Those files are composed of many sections.  I'll just go over a few of them:
</p>
<h4>The code: <tt>.text</tt>
</h4>
<p>This section is the actual code of your library or program it contains all the instructions for 
each function. That part of the code is mapped into memory, and shared between the instances
of the processes that uses it (provided the library is compiled as position independent, which is 
usually the case).</p>
<p>I am not interested in the code in this blog post, let us move to the data sections.</p>
<h4>The read-only data: <tt>.rodata</tt>
</h4>
<p>This section will be loaded the same way as the <tt>.text</tt> section is loaded.
It will also be shared between processes.</p>
<p>It contains the arrays that are marked as <code>const</code> such as <code>string_data</code> and
<code>even_numbers</code>.</p>
<pre class="brush: asm">
.section    .rodata
_ZL11string_data:
    .string "hello world"
_ZL12even_numbers:
    .long   0
    .long   2
    .long   4
    .long   6
    .long   8
</pre>
<p>
You can see that even if the <code>even_numbers</code> array was initialized with multiplications, the
compiler was able to optimize and generate the array at compile time.</p>
<p>The <code>_ZL11</code> that is part of the name is the
<a href="http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B">mangling</a>
because it is <code>const</code>.</p>
<h4>Writable data: <tt>.data</tt>
</h4>
<p>The data section will contain the pre-initialized data that are not read-only.<br/>
This section is not shared between processes but copied for each instance of
processes that uses it.
(Actually, with the copy-on-write optimization in the kernel, it might need to be copied only if the
data changes.)</p>
<p>There goes our <tt>all_number</tt> array that has not been declared as <code>const</code>.</p>
<pre class="brush: asm">
.data
all_numbers:
    .long   0
    .long   1
    .long   2
    .long   3
    .long   4
</pre>
<h4>Initialized at run-time: <tt>.bss</tt> + <tt>.ctors</tt>
</h4>
<p>The compiler was not able to optimize the calls to <code>odd()</code>, it has to be 
computed at run-time.
Where will our <code>odd_numbers</code> array be stored?</p>
<p>What will happen is that it will not be stored in the binary, but some space will be reserved in 
the <tt>.bss</tt> section.  That section is just some memory which is allocated to each process, it
is initialized to 0.</p>
<p>The binary also contains a section with code that is going to be executed before
<code>main()</code> is being called.</p>
<pre class="brush: asm">
.section    .text.startup
_GLOBAL__sub_I_odd_numbers:
    movl    $1, _ZL11odd_numbers(%rip)
    movl    $3, _ZL11odd_numbers+4(%rip)
    movl    $5, _ZL11odd_numbers+8(%rip)
    movl    $7, _ZL11odd_numbers+12(%rip)
    movl    $9, _ZL11odd_numbers+16(%rip)
    ret

.section    .ctors,"aw",@progbits
    .quad   _GLOBAL__sub_I_odd_numbers

.local  _ZL11odd_numbers  ; reserve 20 bytes in the .bss section
    .comm   _ZL11odd_numbers,20,16
</pre>
<p>The <tt>.ctor</tt> section contains a table of pointers to functions that are going
to be called by the loader before it calls <code>main()</code>. In our case, there is only one,
the code that initializes the <code>odd_numbers</code> array.
</p>
<h2>Global Object</h2>
<p>
How about our <code>QString</code>?
It is a global C++ object with a constructor and destructor.
It is simply initialized by running the constructor at start-up.
</p>
<pre class="brush: asm">
.section    .rodata.str1.1,"aMS",@progbits,1
.LC0:
    .string "hello QString"

.section    .text.startup,"ax",@progbits
_GLOBAL__sub_I_qstring_data:
       ; QString constructor (inlined)
    movl    $-1, %esi
    movl    $.LC0, %edi
    call    _ZN7QString16fromAscii_helperEPKci
    movq    %rax, _ZL12qstring_data(%rip)
       ; register the destructor
    movl    $__dso_handle, %edx
    movl    $_ZL12qstring_data, %esi
    movl    $_ZN7QStringD1Ev, %edi
    jmp __cxa_atexit   ; (tail call)
</pre>
<p>Here is the code of the constructor, which have been inlined.</p>
<p>We can also see that the code calls the function <code>__cxa_atexit</code> with the parameters
<code>$_ZL12qstring_data</code> and <code>$_ZN7QStringD1Ev</code>
Which are respectively the address of the QString object, and a function pointer of the 
<code>QString</code> destructor.
In other words, this code registers the destructor of QString to be run on exit.<br/>
The third parameter <code>$__dso_handle</code> is a handle to this dynamic shared object 
(used to run the destructor when a plugin is unloaded for example).
</p>
<h3>What is the problem with global objects with constructor?</h3>
<ul>
    <li>The order in which the constructors are called are not specified by the 
C++ standard. 
If you have dependencies between your global objects, you will run into trouble.
</li>
    <li>All the constructors of all the global in all the libraries need to be run 
before <code>main()</code> and slow down the startup of the application.
(Even for objects that will never be used).
</li>
</ul>
<p>This is why it is not recommended to have global objects in libraries. 
Instead, one can use function static objects, which are initialized on the first use.
(Qt provides a macro for that: 
<a href="http://doc-snapshot.qt-project.org/qt5-stable/qtcore/qglobalstatic.html">
        <code>Q_GLOBAL_STATIC</code>
    </a> 
which is made public in Qt 5.1.)
</p>
<h2>Here comes C++11</h2>
<p>C++11 comes with a new feature: <b>
        <tt>constexpr</tt>
    </b>
</p>
<p>That keyword can be used in two ways: If you specify that a function is a 
<tt>constexpr</tt> it means that the function can be run at compile-time.
<br/>
If you specify that a variable is a <tt>constexpr</tt>, then it means it can be 
computed at compile time.</p>
<p>Let us slightly modify the example above and see what it does:</p>
<pre class="brush: cpp">
static inline constexpr int odd(int n) { return n*2 + 1; }
constexpr int odd_numbers[] = { odd(0), odd(1), odd(2), odd(3), odd(4) };
</pre>
<p>Two <tt>constexpr</tt> were added.</p>
<pre class="brush: asm">
.section    .rodata
_ZL11odd_numbers:
    .long   1
    .long   3
    .long   5
    .long   7
    .long   9
</pre>
<p>Now they are generated at compile time.</p>
<p>If a class has a constructor that is declared as <tt>constexpr</tt> and has no destructor,
you can have this as global object and it will be initialized at compile time.</p>
<p>Since Qt 4.8, there is a macro <a href="http://qt-project.org/doc/qt-5.0/qtcore/qtglobal.html#Q_DECL_CONSTEXPR">
        <tt>Q_DECL_CONSTEXPR</tt>
    </a> which expands to
<code>constexpr</code> if the compiler supports it, or to nothing otherwise.</p>
]]></description></item>
<item><title>Property Bindings and Declarative Syntax in C++</title><link>http://woboq.com/blog/property-bindings-in-cpp.html</link><pubDate>Thu, 28 Feb 2013 08:02:23 GMT</pubDate><description><![CDATA[

<div class="intro">
<p> QtQuick and QML form a really nice language to develop user interfaces.
The QML Bindings are very productive and convenient. The declarative syntax is really a pleasure to work with.<br/>
Would it be possible to do the same in C++?
In this blog post, I will show a working implementation of property bindings in pure C++.</p>

<p><em>Disclaimer:</em> This was done for the fun of it and is not made for production.</p>
</div>

<div class="woboq_hidden">
If you read this article from the RSS, you may want to open it in its
<a href="http://woboq.com/blog/property-bindings-in-cpp.html">original URL</a>
to see property formatted code.</div>

<h2>Bindings</h2>

<p>The goal of bindings is to have one property which depends on other properties.
   When its dependencies are changed, the property is automatically updated.</p>
   
   <p>Here is an example inspired from the
   <a href="http://qt-project.org/doc/qt-4.8/propertybinding.html#property-binding">QML documentation</a>.</p>

  <pre class="code"><em>int</em> <dfn class="decl def" id="_Z13calculateAreaii" title='calculateArea' data-ref="_Z13calculateAreaii" >calculateArea</dfn>(<em>int</em> <dfn class="local col1 ref" id="1width" title='width' data-type='int' data-ref="1width" >width</dfn>, <em>int</em> <dfn class="local col2 ref" id="2height" title='height' data-type='int' data-ref="2height" >height</dfn>) {
  <b>return</b> (<span class="local col1 ref" title='width' data-ref="1width" >width</span> * <span class="local col2 ref" title='height' data-ref="2height" >height</span>) * <var>0.5</var>;
}

<b>struct</b> <dfn class="type def" id="rectangle" title='rectangle' data-ref="rectangle" >rectangle</dfn> {
  <span class="type" title='property' data-ref="property" >property</span>&lt;<span class="type" title='rectangle' data-ref="rectangle" >rectangle</span>*&gt; <dfn class="tu decl" id="rectangle::parent" title='rectangle::parent' data-type='property&lt;rectangle *&gt;' data-ref="rectangle::parent" >parent</dfn> = <b>nullptr</b>;
  <span class="type" title='property' data-ref="property" >property</span>&lt;<em>int</em>&gt; <dfn class="tu decl" id="rectangle::width" title='rectangle::width' data-type='property&lt;int&gt;' data-ref="rectangle::width" >width</dfn> = <var>150</var>;
  <span class="type" title='property' data-ref="property" >property</span>&lt;<em>int</em>&gt; <dfn class="tu decl" id="rectangle::height" title='rectangle::height' data-type='property&lt;int&gt;' data-ref="rectangle::height" >height</dfn> = <var>75</var>;
  <span class="type" title='property' data-ref="property" >property</span>&lt;<em>int</em>&gt; <dfn class="tu decl" id="rectangle::area" title='rectangle::area' data-type='property&lt;int&gt;' data-ref="rectangle::area" >area</dfn> = <dfn class="tu decl def" id="_ZNK9rectangle4areaMUlvE_clEv" title='rectangle::&lt;anonymous class&gt;::operator()' data-type='int rectangle::&lt;anonymous class&gt;::operator()() const' data-ref="_ZNK9rectangle4areaMUlvE_clEv" >[&amp;]</dfn>{ <b>return</b> <span class="ref" title='calculateArea' data-ref="_Z13calculateAreaii" >calculateArea</span>(<span class="tu ref" title='rectangle::width' data-ref="rectangle::width" >width</span>, <span class="tu ref" title='rectangle::height' data-ref="rectangle::height" >height</span>); };

  <span class="type" title='property' data-ref="property" >property</span>&lt;<span class="namespace">std::</span><a class="typedef" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/stringfwd.h.html#std::string" title='std::string' data-ref="std::string" data-proj="include" >string</a>&gt; <dfn class="tu decl" id="rectangle::color" title='rectangle::color' data-type='property&lt;std::string&gt;' data-ref="rectangle::color" >color</dfn> = <dfn class="tu decl def" id="_ZNK9rectangle5colorMUlvE_clEv" title='rectangle::&lt;anonymous class&gt;::operator()' data-type='std::string rectangle::&lt;anonymous class&gt;::operator()() const' data-ref="_ZNK9rectangle5colorMUlvE_clEv" >[&amp;]</dfn>{
    <b>if</b> (<span class="tu ref" title='rectangle::parent' data-ref="rectangle::parent" >parent</span><span class="ref" title='property::operator()' data-ref="_ZNK8propertyclEv" >()</span> &amp;&amp; <span class="tu ref" title='rectangle::area' data-ref="rectangle::area" >area</span> &gt; <span class="tu ref" title='rectangle::parent' data-ref="rectangle::parent" >parent</span><span class="ref" title='property::operator()' data-ref="_ZNK8propertyclEv" >()</span>-&gt;<span class="tu ref" title='rectangle::area' data-ref="rectangle::area" >area</span>)
      <b>return</b> <span class="namespace">std::</span><a class="typedef" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/stringfwd.h.html#std::string" title='std::string' data-ref="std::string" data-proj="include" >string</a>(<q>"blue"</q>);
    <b>else</b>
      <b>return</b> <span class="namespace">std::</span><a class="typedef" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/stringfwd.h.html#std::string" title='std::string' data-ref="std::string" data-proj="include" >string</a>(<q>"red"</q>);
  };
};
</pre>

<p>If you are not familiar with the <code>[&amp;]{ ... }</code> syntax, this is a
<a href="http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11">lambda function</a>.
I'm also using the fact that in C++11, you can initialize the
  members directly in the declaration.</p>

<p>
Now, we'll see how this property class works. At the end I will show a cool demo of what you can do.
</p>

<p>The code is using lots of C++11 constructs. It has been tested with GCC 4.7 and Clang 3.2.</p>


<h2>Property</h2>
<p>I have used my knowledge from QML and the QObject system to build something similar with C++ bindings.<br/>
The goal is to make a proof of concept. It is not optimized. I just wanted to have comprehensible code for this demo.</p>

<p>The idea behind the <code>property</code> class is the same as in QML.  Each property keeps a list of its dependencies.
When a binding is evaluated, all access to the property will be recorded as dependencies.</p>

<p><code>property&lt;T&gt;</code> is a template class. The common part is put in a base class: <code>property_base</code>.</p>



<pre class="code"><b>class</b> <dfn class="type def" id="property_base" title='property_base' data-ref="property_base" >property_base</dfn>
{
  <i>/* Set of properties which are subscribed to this one.</i>
<i>     When this property is changed, subscriptions are refreshed */</i>
  <span class="namespace">std::</span><a class="type" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/unordered_set.h.html#std::unordered_set" title='std::unordered_set' data-ref="std::unordered_set" data-proj="include" >unordered_set</a>&lt;<a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base" title='property_base' data-ref="property_base" >property_base</a> *&gt; <dfn class="decl" id="property_base::subscribers" title='property_base::subscribers' data-ref="property_base::subscribers" >subscribers</dfn>;

  <i>/* Set of properties this property is depending on. */</i>
  <span class="namespace">std::</span><a class="type" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/unordered_set.h.html#std::unordered_set" title='std::unordered_set' data-ref="std::unordered_set" data-proj="include" >unordered_set</a>&lt;<a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base" title='property_base' data-ref="property_base" >property_base</a> *&gt; <dfn class="decl" id="property_base::dependencies" title='property_base::dependencies' data-ref="property_base::dependencies" >dependencies</dfn>;

<b>public</b>:
  <b>virtual</b> <dfn class="virtual decl def" id="_ZN13property_baseD1Ev" title='property_base::~property_base' data-ref="_ZN13property_baseD1Ev" >~</dfn>property_base()
  { <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base16clearSubscribersEv" title='property_base::clearSubscribers' data-ref="_ZN13property_base16clearSubscribersEv" >clearSubscribers</a>(); <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base17clearDependenciesEv" title='property_base::clearDependencies' data-ref="_ZN13property_base17clearDependenciesEv" >clearDependencies</a>(); }

  <i>// re-evaluate this property</i>
  <b>virtual</b> <em>void</em> <dfn class="virtual decl" id="_ZN13property_base8evaluateEv" title='property_base::evaluate' data-ref="_ZN13property_base8evaluateEv" >evaluate</dfn>() = <var>0</var>;
   
<i>  // [...]</i>
<b>protected</b>:
  <i>/* This function is called by the derived class when the property has changed</i>
<i>     The default implementation re-evaluates all the property subscribed to this one. */</i>
  <b>virtual</b> <em>void</em> <dfn class="virtual decl def" id="_ZN13property_base6notifyEv" title='property_base::notify' data-ref="_ZN13property_base6notifyEv" >notify</dfn>() {
    <em>auto</em> <dfn class="local col3 ref" id="3copy" title='copy' data-type='std::unordered_set&lt;property_base *, std::hash&lt;property_base *&gt;, std::equal_to&lt;property_base *&gt;, std::allocator&lt;property_base *&gt; &gt;' data-ref="3copy" >copy</dfn> = <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::subscribers" title='property_base::subscribers' data-ref="property_base::subscribers" >subscribers</a>;
    <b>for</b> (<a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base" title='property_base' data-ref="property_base" >property_base</a> *<dfn class="local col4 ref" id="4p" title='p' data-type='property_base *' data-ref="4p" >p</dfn> : <a class="local col3 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#3copy" title='copy' data-ref="3copy" >copy</a>) {
      <a class="local col4 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#4p" title='p' data-ref="4p" >p</a>-&gt;<a class="virtual member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base8evaluateEv" title='property_base::evaluate' data-ref="_ZN13property_base8evaluateEv" >evaluate</a>();
    }
  }

  <i>/* Derived class call this function whenever this property is accessed.</i>
<i>     It register the dependencies. */</i>
  <em>void</em> <dfn class="decl def" id="_ZN13property_base8accessedEv" title='property_base::accessed' data-ref="_ZN13property_base8accessedEv" >accessed</dfn>() {
    <b>if</b> (<a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base7currentE" title='property_base::current' data-ref="_ZN13property_base7currentE" >current</a> &amp;&amp; <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base7currentE" title='property_base::current' data-ref="_ZN13property_base7currentE" >current</a> != <b>this</b>) {
      <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::subscribers" title='property_base::subscribers' data-ref="property_base::subscribers" >subscribers</a>.<a class="ref" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/hashtable.h.html#_ZNSt10_Hashtable6insertERKT0_" title='std::_Hashtable::insert' data-ref="_ZNSt10_Hashtable6insertERKT0_" data-proj="include" >insert</a>(<a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base7currentE" title='property_base::current' data-ref="_ZN13property_base7currentE" >current</a>);
      <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base7currentE" title='property_base::current' data-ref="_ZN13property_base7currentE" >current</a>-&gt;<a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::dependencies" title='property_base::dependencies' data-ref="property_base::dependencies" >dependencies</a>.<a class="ref" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/unordered_set.h.html#_ZNSt15__unordered_set6insertEONSt10_HashtableIT_S1_T2_St9_IdentityIS1_ET1_T0_NSt8__detail18_Mod_range_hashingENS7_20_Default_ranged_hashENS7_20_Prime_rehash_policyEXT3_ELb1ELb1EE10value_typeE" title='std::__unordered_set::insert' data-ref="_ZNSt15__unordered_set6insertEONSt10_HashtableIT_S1_T2_St9_IdentityIS1_ET1_T0_NSt8__detail18_Mod_range_hashingENS7_20_Default_ranged_hashENS7_20_Prime_rehash_policyEXT3_ELb1ELb1EE10value_typeE" data-proj="include" >insert</a>(<b>this</b>);
    }
  }

  <em>void</em> <dfn class="decl def" id="_ZN13property_base16clearSubscribersEv" title='property_base::clearSubscribers' data-ref="_ZN13property_base16clearSubscribersEv" >clearSubscribers</dfn>() {
      <b>for</b> (<a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base" title='property_base' data-ref="property_base" >property_base</a> *<dfn class="local col5 ref" id="5p" title='p' data-type='property_base *' data-ref="5p" >p</dfn> : <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::subscribers" title='property_base::subscribers' data-ref="property_base::subscribers" >subscribers</a>)
          <a class="local col5 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#5p" title='p' data-ref="5p" >p</a>-&gt;<a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::dependencies" title='property_base::dependencies' data-ref="property_base::dependencies" >dependencies</a>.<a class="ref" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/hashtable.h.html#_ZNSt10_Hashtable5eraseERKT_" title='std::_Hashtable::erase' data-ref="_ZNSt10_Hashtable5eraseERKT_" data-proj="include" >erase</a>(<b>this</b>);
      <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::subscribers" title='property_base::subscribers' data-ref="property_base::subscribers" >subscribers</a>.<a class="ref" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/hashtable.h.html#_ZNSt10_Hashtable5clearEv" title='std::_Hashtable::clear' data-ref="_ZNSt10_Hashtable5clearEv" data-proj="include" >clear</a>();
  }
  <em>void</em> <dfn class="decl def" id="_ZN13property_base17clearDependenciesEv" title='property_base::clearDependencies' data-ref="_ZN13property_base17clearDependenciesEv" >clearDependencies</dfn>() {
      <b>for</b> (<a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base" title='property_base' data-ref="property_base" >property_base</a> *<dfn class="local col6 ref" id="6p" title='p' data-type='property_base *' data-ref="6p" >p</dfn> : <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::dependencies" title='property_base::dependencies' data-ref="property_base::dependencies" >dependencies</a>)
          <a class="local col6 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#6p" title='p' data-ref="6p" >p</a>-&gt;<a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::subscribers" title='property_base::subscribers' data-ref="property_base::subscribers" >subscribers</a>.<a class="ref" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/hashtable.h.html#_ZNSt10_Hashtable5eraseERKT_" title='std::_Hashtable::erase' data-ref="_ZNSt10_Hashtable5eraseERKT_" data-proj="include" >erase</a>(<b>this</b>);
      <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::dependencies" title='property_base::dependencies' data-ref="property_base::dependencies" >dependencies</a>.<a class="ref" href="http://code.woboq.org/kde/include/c++/4.7.2/bits/hashtable.h.html#_ZNSt10_Hashtable5clearEv" title='std::_Hashtable::clear' data-ref="_ZNSt10_Hashtable5clearEv" data-proj="include" >clear</a>();
  }

  <i>/* Helper class that is used on the stack to set the current property being evaluated */</i>
  <b>struct</b> <dfn class="type def" id="property_base::evaluation_scope" title='property_base::evaluation_scope' data-ref="property_base::evaluation_scope" >evaluation_scope</dfn> {
    <dfn class="decl def" id="_ZN13property_base16evaluation_scopeC1EPS_" title='property_base::evaluation_scope::evaluation_scope' data-ref="_ZN13property_base16evaluation_scopeC1EPS_" >evaluation_scope</dfn>(<a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base" title='property_base' data-ref="property_base" >property_base</a> *<dfn class="local col7 ref" id="7prop" title='prop' data-type='property_base *' data-ref="7prop" >prop</dfn>) : <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::evaluation_scope::previous" title='property_base::evaluation_scope::previous' data-ref="property_base::evaluation_scope::previous" >previous</a>(<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base7currentE" title='property_base::current' data-ref="_ZN13property_base7currentE" >current</a>) {
      <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base7currentE" title='property_base::current' data-ref="_ZN13property_base7currentE" >current</a> = <a class="local col7 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#7prop" title='prop' data-ref="7prop" >prop</a>;
    }
    <dfn class="decl def" id="_ZN13property_base16evaluation_scopeD1Ev" title='property_base::evaluation_scope::~evaluation_scope' data-ref="_ZN13property_base16evaluation_scopeD1Ev" >~</dfn>evaluation_scope() { <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base7currentE" title='property_base::current' data-ref="_ZN13property_base7currentE" >current</a> = <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::evaluation_scope::previous" title='property_base::evaluation_scope::previous' data-ref="property_base::evaluation_scope::previous" >previous</a>; }
    <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base" title='property_base' data-ref="property_base" >property_base</a> *<dfn class="decl" id="property_base::evaluation_scope::previous" title='property_base::evaluation_scope::previous' data-ref="property_base::evaluation_scope::previous" >previous</dfn>;
  };
<b>private</b>:
  <b>friend</b> <b>struct</b> <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::evaluation_scope" title='property_base::evaluation_scope' data-ref="property_base::evaluation_scope" >evaluation_scope</a>;
  <i>/* thread_local */</i> <em>static</em> <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base" title='property_base' data-ref="property_base" >property_base</a> *<dfn class="ref" id="_ZN13property_base7currentE" title='property_base::current' data-ref="_ZN13property_base7currentE" >current</dfn>;
};
</pre>

<p>Then we have the implementation of the class <code>property</code>.</p>

<pre class="code"><b>template</b> &lt;<b>typename</b> T&gt;
<b>struct</b> <dfn class="type def" id="property" title='property' data-ref="property" >property</dfn> : <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base" title='property_base' data-ref="property_base" >property_base</a> {
  <b>typedef</b> <span class="namespace">std::</span><a class="type" href="http://code.woboq.org/kde/include/c++/4.7.2/functional.html#std::function" title='std::function' data-ref="std::function" data-proj="include" >function</a>&lt;T()&gt; <dfn class="typedef" id="property::binding_t" title='property::binding_t' data-ref="property::binding_t" >binding_t</dfn>;

  <dfn class="decl" id="_ZN8propertyC1Ev" title='property::property&lt;T&gt;' data-ref="_ZN8propertyC1Ev" >property</dfn>() = <b>default</b>;
  <dfn class="decl def" id="_ZN8propertyC1ERKT_" title='property::property&lt;T&gt;' data-ref="_ZN8propertyC1ERKT_" >property</dfn>(<em>const</em> T &amp;<dfn class="local col8 ref" id="8t" title='t' data-type='const T &amp;' data-ref="8t" >t</dfn>) : <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::value" title='property::value' data-ref="property::value" >value</a>(<a class="local col8 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#8t" title='t' data-ref="8t" >t</a>) {}
  <dfn class="decl def" id="_ZN8propertyC1ERKSt8functionIFT_vEE" title='property::property&lt;T&gt;' data-ref="_ZN8propertyC1ERKSt8functionIFT_vEE" >property</dfn>(<em>const</em> <a class="typedef" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::binding_t" title='property::binding_t' data-ref="property::binding_t" >binding_t</a> &amp;<dfn class="local col9 ref" id="9b" title='b' data-type='const binding_t &amp;' data-ref="9b" >b</dfn>) : <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::binding" title='property::binding' data-ref="property::binding" >binding</a>(<a class="local col9 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#9b" title='b' data-ref="9b" >b</a>) { <a class="virtual member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN8property8evaluateEv" title='property::evaluate' data-ref="_ZN8property8evaluateEv" >evaluate</a>(); }

  <em>void</em> <dfn class="decl def" id="_ZN8propertyaSERKT_" title='property::operator=' data-ref="_ZN8propertyaSERKT_" ><b>operator</b>=</dfn>(<em>const</em> T &amp;<dfn class="local col0 ref" id="10t" title='t' data-type='const T &amp;' data-ref="10t" >t</dfn>) {
      <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::value" title='property::value' data-ref="property::value" >value</a> = <a class="local col0 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#10t" title='t' data-ref="10t" >t</a>;
      <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base17clearDependenciesEv" title='property_base::clearDependencies' data-ref="_ZN13property_base17clearDependenciesEv" >clearDependencies</a>();
      <a class="virtual member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base6notifyEv" title='property_base::notify' data-ref="_ZN13property_base6notifyEv" >notify</a>();
  }
  <em>void</em> <dfn class="decl def" id="_ZN8propertyaSERKSt8functionIFT_vEE" title='property::operator=' data-ref="_ZN8propertyaSERKSt8functionIFT_vEE" ><b>operator</b>=</dfn>(<em>const</em> <a class="typedef" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::binding_t" title='property::binding_t' data-ref="property::binding_t" >binding_t</a> &amp;<dfn class="local col1 ref" id="11b" title='b' data-type='const binding_t &amp;' data-ref="11b" >b</dfn>) {
      <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::binding" title='property::binding' data-ref="property::binding" >binding</a> = <a class="local col1 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#11b" title='b' data-ref="11b" >b</a>;
      <a class="virtual member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN8property8evaluateEv" title='property::evaluate' data-ref="_ZN8property8evaluateEv" >evaluate</a>();
  }

  <em>const</em> T &amp;<dfn class="decl def" id="_ZNK8property3getEv" title='property::get' data-ref="_ZNK8property3getEv" >get</dfn>() <em>const</em> {
    <b>const_cast</b>&lt;property*&gt;(<b>this</b>)-&gt;accessed();
    <b>return</b> <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::value" title='property::value' data-ref="property::value" >value</a>;
  }

  <i>//automatic conversions</i>
  <em>const</em> T &amp;<dfn class="decl def" id="_ZNK8propertyclEv" title='property::operator()' data-ref="_ZNK8propertyclEv" ><b>operator</b>()</dfn>() <em>const</em> { <b>return</b> <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZNK8property3getEv" title='property::get' data-ref="_ZNK8property3getEv" >get</a>();  }
  <dfn class="decl def" id="_ZNK8propertycvRKT_Ev" title='property::operator const type-parameter-0-0 &amp;' data-ref="_ZNK8propertycvRKT_Ev" ><b>operator</b> <em>const</em> T&amp;</dfn>() <em>const</em> { <b>return</b> <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZNK8property3getEv" title='property::get' data-ref="_ZNK8property3getEv" >get</a>(); }

  <em>void</em> <dfn class="virtual decl def" id="_ZN8property8evaluateEv" title='property::evaluate' data-ref="_ZN8property8evaluateEv" >evaluate</dfn>() override {
    <b>if</b> (<a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::binding" title='property::binding' data-ref="property::binding" >binding</a>) {
      <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base17clearDependenciesEv" title='property_base::clearDependencies' data-ref="_ZN13property_base17clearDependenciesEv" >clearDependencies</a>();
      <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_base::evaluation_scope" title='property_base::evaluation_scope' data-ref="property_base::evaluation_scope" >evaluation_scope</a> <dfn class="local col6 ref" id="16scope" title='scope' data-type='property_base::evaluation_scope' data-ref="16scope" >scope</dfn>(<b>this</b>);
      <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::value" title='property::value' data-ref="property::value" >value</a> = <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::binding" title='property::binding' data-ref="property::binding" >binding</a>();
    }
    <a class="virtual member" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#_ZN13property_base6notifyEv" title='property_base::notify' data-ref="_ZN13property_base6notifyEv" >notify</a>();
  }

<b>protected</b>:
  T <dfn class="decl" id="property::value" title='property::value' data-ref="property::value" >value</dfn>;
  <a class="typedef" href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property::binding_t" title='property::binding_t' data-ref="property::binding_t" >binding_t</a> <dfn class="decl" id="property::binding" title='property::binding' data-ref="property::binding" >binding</dfn>;
};
</pre>

<h3><code>property_hook</code></h3>

<p>It is also desirable to be notified when a property is changed, so we can for example call <code>update()</code>.
The <code><a href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property.h.html#property_hook">property_hook</a></code> class lets you specify a function which will be called when the property changes.
</p>

<h2>Qt bindings</h2>

<p>Now that we have the <code>property</code> class, we can build everything on top of that.
We could build for example a set of widgets and use those.  I'm going to use Qt Widgets for that.  
If the QtQuick elements had a C++ API, I could have used those instead.</p>

<h3>The <code>property_qobject</code></h3>

<p>I introduce a
<code><a href="http://woboq.com/blog/property-bindings-in-cpp/code/src/property_qobject.h.html#property_qobject">property_qobject</a></code> 
which is basically wrapping a property in a QObject. You initialize it by passing a
pointer to the QObject and the string of the property you want to track, and voil&#224;.</p>

<p>The implementation is not efficient and it could be optimized by sharing the QObject rather than having one for each property.
With Qt5 I could also connect to lambda instead of doing this hack, but I used Qt 4.8 here.</p>


<h3>Wrappers</h3>

<p>Then I create a wrapper around each class I'm going to use that expose the properties in a <code>property_qobject</code></p>

<h2>A Demo</h2>

<p>Now let's see what we are capable of doing:</p>
<p>This small demo just has a line edit which lets you specify a color and few sliders to change 
the rotation and the opacity of a graphics item.</p>

<center><img src="http://woboq.com/blog/property-bindings-in-cpp/demo.png" style="margin:0.5ex; box-shadow: 1px 1px 2px 2px #ccc;"/></center>

<p>Let the code speak for itself.</p>
<p>We need a Rectangle object with the proper bindings:</p>

<pre class="code"><b>struct</b> <dfn class="type def" id="GraphicsRectObject" title='GraphicsRectObject' data-ref="GraphicsRectObject" >GraphicsRectObject</dfn> : <a class="type" href="http://code.woboq.org/kde/include/QtGui/qgraphicswidget.h.html#QGraphicsWidget" title='QGraphicsWidget' data-ref="QGraphicsWidget" data-proj="include" >QGraphicsWidget</a> {
  <i data-doc="GraphicsRectObject::geometry">// bind the QObject properties.</i>
  <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#property_qobject" title='property_qobject' data-ref="property_qobject" >property_qobject</a>&lt;<a class="type" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#QRectF" title='QRectF' data-ref="QRectF" data-proj="include" >QRectF</a>&gt; <dfn class="tu decl" id="GraphicsRectObject::geometry" title='GraphicsRectObject::geometry' data-type='property_qobject&lt;QRectF&gt;' data-ref="GraphicsRectObject::geometry" >geometry</dfn> { <b>this</b>, <q>"geometry"</q> };
  <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#property_qobject" title='property_qobject' data-ref="property_qobject" >property_qobject</a>&lt;<a class="typedef" href="http://code.woboq.org/kde/include/QtCore/qglobal.h.html#qreal" title='qreal' data-ref="qreal" data-proj="include" >qreal</a>&gt; <dfn class="tu decl" id="GraphicsRectObject::opacity" title='GraphicsRectObject::opacity' data-type='property_qobject&lt;qreal&gt;' data-ref="GraphicsRectObject::opacity" >opacity</dfn> { <b>this</b>, <q>"opacity"</q> };
  <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#property_qobject" title='property_qobject' data-ref="property_qobject" >property_qobject</a>&lt;<a class="typedef" href="http://code.woboq.org/kde/include/QtCore/qglobal.h.html#qreal" title='qreal' data-ref="qreal" data-proj="include" >qreal</a>&gt; <dfn class="tu decl" id="GraphicsRectObject::rotation" title='GraphicsRectObject::rotation' data-type='property_qobject&lt;qreal&gt;' data-ref="GraphicsRectObject::rotation" >rotation</dfn> { <b>this</b>, <q>"rotation"</q> };

  <i>// add a color property, with a hook to update when it changes</i>
  <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#property_hook" title='property_hook' data-ref="property_hook" >property_hook</a>&lt;<a class="type" href="http://code.woboq.org/kde/include/QtGui/qcolor.h.html#QColor" title='QColor' data-ref="QColor" data-proj="include" >QColor</a>&gt; <dfn class="tu decl" id="GraphicsRectObject::color" title='GraphicsRectObject::color' data-type='property_hook&lt;QColor&gt;' data-ref="GraphicsRectObject::color" >color</dfn> { <dfn class="tu decl def" id="_ZNK18GraphicsRectObject5colorMUlvE_clEv" title='GraphicsRectObject::&lt;anonymous class&gt;::operator()' data-type='void GraphicsRectObject::&lt;anonymous class&gt;::operator()() const' data-ref="_ZNK18GraphicsRectObject5colorMUlvE_clEv" >[<b>this</b>]</dfn>{ <b>this</b>-&gt;<a class="ref" href="http://code.woboq.org/kde/include/QtGui/qgraphicsitem.h.html#_ZN13QGraphicsItem6updateERK6QRectF" title='QGraphicsItem::update' data-ref="_ZN13QGraphicsItem6updateERK6QRectF" data-proj="include" >update</a>(); } };
<b>private</b>:
  <em>void</em> <dfn class="virtual decl def" id="_ZN18GraphicsRectObject5paintEP8QPainterPK24QStyleOptionGraphicsItemP7QWidget" title='GraphicsRectObject::paint' data-ref="_ZN18GraphicsRectObject5paintEP8QPainterPK24QStyleOptionGraphicsItemP7QWidget" >paint</dfn>(<a class="type" href="http://code.woboq.org/kde/include/QtGui/qpainter.h.html#QPainter" title='QPainter' data-ref="QPainter" data-proj="include" >QPainter</a>* <dfn class="local col8 ref" id="48painter" title='painter' data-type='QPainter *' data-ref="48painter" >painter</dfn>, <em>const</em> <a class="type" href="http://code.woboq.org/kde/include/QtGui/qstyleoption.h.html#QStyleOptionGraphicsItem" title='QStyleOptionGraphicsItem' data-ref="QStyleOptionGraphicsItem" data-proj="include" >QStyleOptionGraphicsItem</a>* <dfn class="local col9 ref" id="49option" title='option' data-type='const QStyleOptionGraphicsItem *' data-ref="49option" >option</dfn>, <a class="type" href="http://code.woboq.org/kde/include/QtGui/qwidget.h.html#QWidget" title='QWidget' data-ref="QWidget" data-proj="include" >QWidget</a>*) override {
    <a class="local col8 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#48painter" title='painter' data-ref="48painter" >painter</a>-&gt;<a class="ref" href="http://code.woboq.org/kde/include/QtGui/qpainter.h.html#_ZN8QPainter8setBrushERK6QBrush" title='QPainter::setBrush' data-ref="_ZN8QPainter8setBrushERK6QBrush" data-proj="include" >setBrush</a>(<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#GraphicsRectObject::color" title='GraphicsRectObject::color' data-ref="GraphicsRectObject::color" >color</a><a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZNK8propertyclEv" title='property::operator()' data-ref="_ZNK8propertyclEv" >()</a>);
    <a class="local col8 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#48painter" title='painter' data-ref="48painter" >painter</a>-&gt;<a class="ref" href="http://code.woboq.org/kde/include/QtGui/qpainter.h.html#_ZN8QPainter8drawRectERK6QRectF" title='QPainter::drawRect' data-ref="_ZN8QPainter8drawRectERK6QRectF" data-proj="include" >drawRect</a>(<a class="virtual member" href="http://code.woboq.org/kde/include/QtGui/qgraphicswidget.h.html#_ZNK15QGraphicsWidget12boundingRectEv" title='QGraphicsWidget::boundingRect' data-ref="_ZNK15QGraphicsWidget12boundingRectEv" data-proj="include" >boundingRect</a>());
  }
};
</pre>

<p>Then we can proceed and declare a window object with all the subwidgets:</p>

<pre class="code"><b>struct</b> <dfn class="type def" id="MyWindow" title='MyWindow' data-ref="MyWindow" >MyWindow</dfn> : <a class="typedef" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#Widget" title='Widget' data-ref="Widget" >Widget</a> {
  <a class="typedef" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#LineEdit" title='LineEdit' data-ref="LineEdit" >LineEdit</a> <dfn class="tu decl" id="MyWindow::colorEdit" title='MyWindow::colorEdit' data-type='LineEdit' data-ref="MyWindow::colorEdit" >colorEdit</dfn> {<b>this</b>};

  <a class="typedef" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#Slider" title='Slider' data-ref="Slider" >Slider</a> <dfn class="tu decl" id="MyWindow::rotationSlider" title='MyWindow::rotationSlider' data-type='Slider' data-ref="MyWindow::rotationSlider" >rotationSlider</dfn> {<span class="namespace">Qt::</span><a class="enum" href="http://code.woboq.org/kde/include/QtCore/qnamespace.h.html#Qt::Orientation::Horizontal" title='Qt::Orientation::Horizontal' data-ref="Qt::Orientation::Horizontal" data-proj="include" >Horizontal</a>, <b>this</b>};
  <a class="typedef" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#Slider" title='Slider' data-ref="Slider" >Slider</a> <dfn class="tu decl" id="MyWindow::opacitySlider" title='MyWindow::opacitySlider' data-type='Slider' data-ref="MyWindow::opacitySlider" >opacitySlider</dfn> {<span class="namespace">Qt::</span><a class="enum" href="http://code.woboq.org/kde/include/QtCore/qnamespace.h.html#Qt::Orientation::Horizontal" title='Qt::Orientation::Horizontal' data-ref="Qt::Orientation::Horizontal" data-proj="include" >Horizontal</a>, <b>this</b>};

  <a class="type" href="http://code.woboq.org/kde/include/QtGui/qgraphicsscene.h.html#QGraphicsScene" title='QGraphicsScene' data-ref="QGraphicsScene" data-proj="include" >QGraphicsScene</a> <dfn class="tu decl" id="MyWindow::scene" title='MyWindow::scene' data-type='QGraphicsScene' data-ref="MyWindow::scene" >scene</dfn>;
  <a class="typedef" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#GraphicsView" title='GraphicsView' data-ref="GraphicsView" >GraphicsView</a> <dfn class="tu decl" id="MyWindow::view" title='MyWindow::view' data-type='GraphicsView' data-ref="MyWindow::view" >view</dfn> {&amp;<a class="tu ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::scene" title='MyWindow::scene' data-ref="MyWindow::scene" >scene</a>, <b>this</b>};
  <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#GraphicsRectObject" title='GraphicsRectObject' data-ref="GraphicsRectObject" >GraphicsRectObject</a> <dfn class="tu decl" id="MyWindow::rectangle" title='MyWindow::rectangle' data-type='GraphicsRectObject' data-ref="MyWindow::rectangle" >rectangle</dfn>;

  ::<a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#property" title='property' data-ref="property" >property</a>&lt;<em>int</em>&gt; <dfn class="tu decl" id="MyWindow::margin" title='MyWindow::margin' data-type='::property&lt;int&gt;' data-ref="MyWindow::margin" >margin</dfn> {<var>10</var>};

  <dfn class="tu decl def" id="_ZN8MyWindowC1Ev" title='MyWindow::MyWindow' data-type='void MyWindow::MyWindow()' data-ref="_ZN8MyWindowC1Ev" >MyWindow</dfn>() {
    <i>// Layout the items.  Not really as good as real layouts, but it demonstrates bindings</i>
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::colorEdit" title='MyWindow::colorEdit' data-ref="MyWindow::colorEdit" >colorEdit</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QLineEdit&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZN16property_wrapperaSERKSt8functionIFT_vEE" title='property_wrapper::operator=' data-ref="_ZN16property_wrapperaSERKSt8functionIFT_vEE" >=</a> [&amp;]{ <b>return</b> <a class="type" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#QRect" title='QRect' data-ref="QRect" data-proj="include" >QRect</a>(<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>, <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>,
                                             <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QWidget&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a><a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZNK16property_wrapperclEv" title='property_wrapper::operator()' data-ref="_ZNK16property_wrapperclEv" >()</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#_ZNK5QRect5widthEv" title='QRect::width' data-ref="_ZNK5QRect5widthEv" data-proj="include" >width</a>() - <var>2</var>*<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>,
                                             <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::colorEdit" title='MyWindow::colorEdit' data-ref="MyWindow::colorEdit" >colorEdit</a>.<a class="virtual ref" href="http://code.woboq.org/kde/include/QtGui/qlineedit.h.html#_ZNK9QLineEdit8sizeHintEv" title='QLineEdit::sizeHint' data-ref="_ZNK9QLineEdit8sizeHintEv" data-proj="include" >sizeHint</a>().<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qsize.h.html#_ZNK5QSize6heightEv" title='QSize::height' data-ref="_ZNK5QSize6heightEv" data-proj="include" >height</a>()); };
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rotationSlider" title='MyWindow::rotationSlider' data-ref="MyWindow::rotationSlider" >rotationSlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QSlider&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZN16property_wrapperaSERKSt8functionIFT_vEE" title='property_wrapper::operator=' data-ref="_ZN16property_wrapperaSERKSt8functionIFT_vEE" >=</a> [&amp;]{ <b>return</b> <a class="type" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#QRect" title='QRect' data-ref="QRect" data-proj="include" >QRect</a>(<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>,
                                                  <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::colorEdit" title='MyWindow::colorEdit' data-ref="MyWindow::colorEdit" >colorEdit</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QLineEdit&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a><a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZNK16property_wrapperclEv" title='property_wrapper::operator()' data-ref="_ZNK16property_wrapperclEv" >()</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#_ZNK5QRect6bottomEv" title='QRect::bottom' data-ref="_ZNK5QRect6bottomEv" data-proj="include" >bottom</a>() + <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>,
                                                  <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QWidget&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a><a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZNK16property_wrapperclEv" title='property_wrapper::operator()' data-ref="_ZNK16property_wrapperclEv" >()</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#_ZNK5QRect5widthEv" title='QRect::width' data-ref="_ZNK5QRect5widthEv" data-proj="include" >width</a>() - <var>2</var>*<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>,
                                                  <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rotationSlider" title='MyWindow::rotationSlider' data-ref="MyWindow::rotationSlider" >rotationSlider</a>.<a class="virtual ref" href="http://code.woboq.org/kde/include/QtGui/qslider.h.html#_ZNK7QSlider8sizeHintEv" title='QSlider::sizeHint' data-ref="_ZNK7QSlider8sizeHintEv" data-proj="include" >sizeHint</a>().<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qsize.h.html#_ZNK5QSize6heightEv" title='QSize::height' data-ref="_ZNK5QSize6heightEv" data-proj="include" >height</a>()); };
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::opacitySlider" title='MyWindow::opacitySlider' data-ref="MyWindow::opacitySlider" >opacitySlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QSlider&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZN16property_wrapperaSERKSt8functionIFT_vEE" title='property_wrapper::operator=' data-ref="_ZN16property_wrapperaSERKSt8functionIFT_vEE" >=</a> [&amp;]{ <b>return</b> <a class="type" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#QRect" title='QRect' data-ref="QRect" data-proj="include" >QRect</a>(<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>,
                                                 <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rotationSlider" title='MyWindow::rotationSlider' data-ref="MyWindow::rotationSlider" >rotationSlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QSlider&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a><a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZNK16property_wrapperclEv" title='property_wrapper::operator()' data-ref="_ZNK16property_wrapperclEv" >()</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#_ZNK5QRect6bottomEv" title='QRect::bottom' data-ref="_ZNK5QRect6bottomEv" data-proj="include" >bottom</a>() + <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>,
                                                 <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QWidget&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a><a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZNK16property_wrapperclEv" title='property_wrapper::operator()' data-ref="_ZNK16property_wrapperclEv" >()</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#_ZNK5QRect5widthEv" title='QRect::width' data-ref="_ZNK5QRect5widthEv" data-proj="include" >width</a>() - <var>2</var>*<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>,
                                                 <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::opacitySlider" title='MyWindow::opacitySlider' data-ref="MyWindow::opacitySlider" >opacitySlider</a>.<a class="virtual ref" href="http://code.woboq.org/kde/include/QtGui/qslider.h.html#_ZNK7QSlider8sizeHintEv" title='QSlider::sizeHint' data-ref="_ZNK7QSlider8sizeHintEv" data-proj="include" >sizeHint</a>().<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qsize.h.html#_ZNK5QSize6heightEv" title='QSize::height' data-ref="_ZNK5QSize6heightEv" data-proj="include" >height</a>()); };
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::view" title='MyWindow::view' data-ref="MyWindow::view" >view</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QGraphicsView&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZN16property_wrapperaSERKSt8functionIFT_vEE" title='property_wrapper::operator=' data-ref="_ZN16property_wrapperaSERKSt8functionIFT_vEE" >=</a> [&amp;]{
        <em>int</em> <dfn class="local col0 ref" id="50x" title='x' data-type='int' data-ref="50x" >x</dfn> = <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::opacitySlider" title='MyWindow::opacitySlider' data-ref="MyWindow::opacitySlider" >opacitySlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QSlider&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a><a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZNK16property_wrapperclEv" title='property_wrapper::operator()' data-ref="_ZNK16property_wrapperclEv" >()</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#_ZNK5QRect6bottomEv" title='QRect::bottom' data-ref="_ZNK5QRect6bottomEv" data-proj="include" >bottom</a>() + <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>;
        <b>return</b> <a class="type" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#QRect" title='QRect' data-ref="QRect" data-proj="include" >QRect</a>(<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>, <a class="local col0 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#50x" title='x' data-ref="50x" >x</a>, <a class="member" href="http://code.woboq.org/kde/include/QtGui/qwidget.h.html#_ZNK7QWidget5widthEv" title='QWidget::width' data-ref="_ZNK7QWidget5widthEv" data-proj="include" >width</a>() - <var>2</var>*<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>, <a class="member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::Widget::geometry" title='QtWrapper::Widget&lt;QWidget&gt;::geometry' data-ref="QtWrapper::Widget::geometry" >geometry</a><a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZNK16property_wrapperclEv" title='property_wrapper::operator()' data-ref="_ZNK16property_wrapperclEv" >()</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtCore/qrect.h.html#_ZNK5QRect6heightEv" title='QRect::height' data-ref="_ZNK5QRect6heightEv" data-proj="include" >height</a>() - <a class="local col0 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#50x" title='x' data-ref="50x" >x</a> - <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::margin" title='MyWindow::margin' data-ref="MyWindow::margin" >margin</a>); 
    };

    <i>// Some proper default value</i>
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::colorEdit" title='MyWindow::colorEdit' data-ref="MyWindow::colorEdit" >colorEdit</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::LineEdit::text" title='QtWrapper::LineEdit&lt;QLineEdit&gt;::text' data-ref="QtWrapper::LineEdit::text" >text</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#_ZN16property_qobjectaSERKT_" title='property_qobject::operator=' data-ref="_ZN16property_qobjectaSERKT_" >=</a> <a class="type" href="http://code.woboq.org/kde/include/QtCore/qstring.h.html#QString" title='QString' data-ref="QString" data-proj="include" >QString</a>(<q>"blue"</q>);
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rotationSlider" title='MyWindow::rotationSlider' data-ref="MyWindow::rotationSlider" >rotationSlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::AbstractSlider::minimum" title='QtWrapper::AbstractSlider&lt;QSlider&gt;::minimum' data-ref="QtWrapper::AbstractSlider::minimum" >minimum</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#_ZN16property_qobjectaSERKT_" title='property_qobject::operator=' data-ref="_ZN16property_qobjectaSERKT_" >=</a> -<var>180</var>;
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rotationSlider" title='MyWindow::rotationSlider' data-ref="MyWindow::rotationSlider" >rotationSlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::AbstractSlider::maximum" title='QtWrapper::AbstractSlider&lt;QSlider&gt;::maximum' data-ref="QtWrapper::AbstractSlider::maximum" >maximum</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#_ZN16property_qobjectaSERKT_" title='property_qobject::operator=' data-ref="_ZN16property_qobjectaSERKT_" >=</a> <var>180</var>;
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::opacitySlider" title='MyWindow::opacitySlider' data-ref="MyWindow::opacitySlider" >opacitySlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::AbstractSlider::minimum" title='QtWrapper::AbstractSlider&lt;QSlider&gt;::minimum' data-ref="QtWrapper::AbstractSlider::minimum" >minimum</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#_ZN16property_qobjectaSERKT_" title='property_qobject::operator=' data-ref="_ZN16property_qobjectaSERKT_" >=</a> <var>0</var>;
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::opacitySlider" title='MyWindow::opacitySlider' data-ref="MyWindow::opacitySlider" >opacitySlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::AbstractSlider::maximum" title='QtWrapper::AbstractSlider&lt;QSlider&gt;::maximum' data-ref="QtWrapper::AbstractSlider::maximum" >maximum</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#_ZN16property_qobjectaSERKT_" title='property_qobject::operator=' data-ref="_ZN16property_qobjectaSERKT_" >=</a> <var>100</var>;
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::opacitySlider" title='MyWindow::opacitySlider' data-ref="MyWindow::opacitySlider" >opacitySlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::AbstractSlider::value" title='QtWrapper::AbstractSlider&lt;QSlider&gt;::value' data-ref="QtWrapper::AbstractSlider::value" >value</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#_ZN16property_qobjectaSERKT_" title='property_qobject::operator=' data-ref="_ZN16property_qobjectaSERKT_" >=</a> <var>100</var>;

    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::scene" title='MyWindow::scene' data-ref="MyWindow::scene" >scene</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtGui/qgraphicsscene.h.html#_ZN14QGraphicsScene7addItemEP13QGraphicsItem" title='QGraphicsScene::addItem' data-ref="_ZN14QGraphicsScene7addItemEP13QGraphicsItem" data-proj="include" >addItem</a>(&amp;<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rectangle" title='MyWindow::rectangle' data-ref="MyWindow::rectangle" >rectangle</a>);

    <i>// now the 'cool' bindings</i>
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rectangle" title='MyWindow::rectangle' data-ref="MyWindow::rectangle" >rectangle</a>.<a class="tu ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#GraphicsRectObject::color" title='GraphicsRectObject::color' data-ref="GraphicsRectObject::color" >color</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property.h.html#_ZN8propertyI6QColorEaSERKT_" title='property&lt;QColor&gt;::operator=' data-ref="_ZN8propertyI6QColorEaSERKT_" >=</a> [&amp;]{ <b>return</b> <a class="type" href="http://code.woboq.org/kde/include/QtGui/qcolor.h.html#QColor" title='QColor' data-ref="QColor" data-proj="include" >QColor</a>(<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::colorEdit" title='MyWindow::colorEdit' data-ref="MyWindow::colorEdit" >colorEdit</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::LineEdit::text" title='QtWrapper::LineEdit&lt;QLineEdit&gt;::text' data-ref="QtWrapper::LineEdit::text" >text</a>);  };
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rectangle" title='MyWindow::rectangle' data-ref="MyWindow::rectangle" >rectangle</a>.<a class="tu ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#GraphicsRectObject::opacity" title='GraphicsRectObject::opacity' data-ref="GraphicsRectObject::opacity" >opacity</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#_ZN16property_qobjectaSERKSt8functionIFT_vEE" title='property_qobject::operator=' data-ref="_ZN16property_qobjectaSERKSt8functionIFT_vEE" >=</a> [&amp;]{ <b>return</b> <a class="typedef" href="http://code.woboq.org/kde/include/QtCore/qglobal.h.html#qreal" title='qreal' data-ref="qreal" data-proj="include" >qreal</a>(<a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::opacitySlider" title='MyWindow::opacitySlider' data-ref="MyWindow::opacitySlider" >opacitySlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::AbstractSlider::value" title='QtWrapper::AbstractSlider&lt;QSlider&gt;::value' data-ref="QtWrapper::AbstractSlider::value" >value</a>/<var>100.</var>); };
    <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rectangle" title='MyWindow::rectangle' data-ref="MyWindow::rectangle" >rectangle</a>.<a class="tu ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#GraphicsRectObject::rotation" title='GraphicsRectObject::rotation' data-ref="GraphicsRectObject::rotation" >rotation</a> <a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#_ZN16property_qobjectaSERKSt8functionIFT_vEE" title='property_qobject::operator=' data-ref="_ZN16property_qobjectaSERKSt8functionIFT_vEE" >=</a> [&amp;]{ <b>return</b> <a class="tu member" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow::rotationSlider" title='MyWindow::rotationSlider' data-ref="MyWindow::rotationSlider" >rotationSlider</a>.<a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/qobject_wrappers.h.html#QtWrapper::AbstractSlider::value" title='QtWrapper::AbstractSlider&lt;QSlider&gt;::value' data-ref="QtWrapper::AbstractSlider::value" >value</a><a class="ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview../../src/property_qobject.h.html#_ZN16property_qobjectclEv" title='property_qobject::operator()' data-ref="_ZN16property_qobjectclEv" >()</a>; };
  }
};

<em>int</em> <dfn class="decl def" id="main" title='main' data-ref="main" >main</dfn>(<em>int</em> <dfn class="local col1 ref" id="51argc" title='argc' data-type='int' data-ref="51argc" >argc</dfn>, <em>char</em> **<dfn class="local col2 ref" id="52argv" title='argv' data-type='char **' data-ref="52argv" >argv</dfn>)
{
    <a class="type" href="http://code.woboq.org/kde/include/QtGui/qapplication.h.html#QApplication" title='QApplication' data-ref="QApplication" data-proj="include" >QApplication</a> <dfn class="local col3 ref" id="53app" title='app' data-type='QApplication' data-ref="53app" >app</dfn>(<a class="local col1 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#51argc" title='argc' data-ref="51argc" >argc</a>,<a class="local col2 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#52argv" title='argv' data-ref="52argv" >argv</a>);
    <a class="type" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#MyWindow" title='MyWindow' data-ref="MyWindow" >MyWindow</a> <dfn class="local col4 ref" id="54window" title='window' data-type='MyWindow' data-ref="54window" >window</dfn>;
    <a class="local col4 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#54window" title='window' data-ref="54window" >window</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtGui/qwidget.h.html#_ZN7QWidget4showEv" title='QWidget::show' data-ref="_ZN7QWidget4showEv" data-proj="include" >show</a>();
    <b>return</b> <a class="local col3 ref" href="http://woboq.com/blog/property-bindings-in-cpp/code/example/graphicsview/graphicsview.cc.html#53app" title='app' data-ref="53app" >app</a>.<a class="ref" href="http://code.woboq.org/kde/include/QtGui/qapplication.h.html#_ZN12QApplication4execEv" title='QApplication::exec' data-ref="_ZN12QApplication4execEv" data-proj="include" >exec</a>();
}
</pre>

<h2>Conclusion</h2>

<p>You can <a href="https://github.com/woboq/property_bindings">clone the code repository </a> and try it for yourself. </p>
<p>Perhaps one day, a library will provide such property bindings.</p>

]]></description></item>
<item><title>QMap vs. QHash: A small benchmark</title><link>http://woboq.com/blog/qmap_qhash_benchmark.html</link><pubDate>Tue, 19 Feb 2013 12:47:23 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>While working on my Qt developer days 2012 presentation <a href="http://www.youtube.com/watch?v=vixQxXCVR10">(QtCore in depth)</a>, 
I made a benchmark comparing QMap and QHash. I thought it would be nice to share the results in this short blog entry.
</p>
</div>
<h2>Under The Hood</h2>
<p>The Qt 4 containers are well explained by <a href="http://doc.qt.digia.com/qq/qq19-containers.html">this old Qt Quarterly article</a>.
</p>
<p>
    <code>QHash</code> is implemented using a <a href="http://en.wikipedia.org/wiki/Hash_table">Hash Table</a> 
and <code>QMap</code> was implemented using a <a href="http://en.wikipedia.org/wiki/Skip_list">Skip list</a> in Qt4.</p>
<p>
In Qt 5, the implementation of the containers have changed a bit, but the concepts are still the same. Here are the main differences:</p>
<ul>
    <li>
        <code>QVector</code>, <code>QString</code> and <code>QByteArray</code> now share the same implementation 
(<a href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qarraydata.h.html#QArrayData">
            <code>QArrayData</code>
        </a>). 
    The main difference is that there is now an <code>offset</code> which might allow in the future to reference external data.</li>
    <li>
        <a href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qmap.h.html#QMap">QMap implementation</a> has totally changed. It is no longer a skip list, but a <a href="http://en.wikipedia.org/wiki/Red-black_tree">red-black tree</a>.</li>
</ul>
<h2>The Benchmark</h2>
<p>The benchmark is simple and is doing lots of look-ups in a loop during one second and count the number of iterations.<br/>
It is not really scientific. The goal is only to show the shape of the curves. </p>
<p>The source: <a href="http://woboq.com/blog/qmap_qhash_benchmark/benchmark.cc.html">benchmark.cc</a>
</p>
<h2>The Result</h2>
<p>Run on my computer, gcc 4.7.
Higher is better.   The number of element is on a logarithmic scale.
For QHash, one should expect it not to change with the number of elements, and for QMap it should be <code>O(log N)</code>: a straight line on a logarithmic scale.

</p>
<h3>Qt 4.8</h3>
<img src="http://woboq.com/blog/qmap_qhash_benchmark/bench-48.png"/>
<p>QMap performs slightly slower than std::map. QMap lookup is faster than in a QHash for less than about 10 elements.</p>
<h3>Qt 5</h3>
<img src="http://woboq.com/blog/qmap_qhash_benchmark/bench-5.png"/>
<p>It was a good idea to change from a skip list to a red-black tree. 
The performance of the Qt containers compared to the STL are about the same.
QMap is faster than QHash if there is less than about 20 elements.</p>
<p>If you compare the number between Qt5 and Qt4 you see that Qt5 performs better. That might be related by the changes in QString.</p>
<h2>Conclusion</h2>
<p>The typical rule is: Use QMap only if you need the items to be sorted or if you know that you always have a very small amount of items in your map.</p>
]]></description></item>
<item><title>You were not doing so wrong.</title><link>http://woboq.com/blog/qthread-you-were-not-doing-so-wrong.html</link><pubDate>Tue, 22 Jan 2013 13:00:00 GMT</pubDate><description><![CDATA[
<div class="intro">
<p>
This post is about the use of QThread. It is an answer to a three years old blog post by Brad, my colleague at the time:<br/>
<a href="http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/"><q>You're doing it wrong</q></a>
</p>
</div>
<img style="float:right; margin-left:2ex" src="http://upload.wikimedia.org/wikipedia/commons/thumb/c/cd/Fil_%C3%A0_tapisserie.jpg/200px-Fil_%C3%A0_tapisserie.jpg" />
<p>In <a href="http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/">his blog post</a>,
Brad explains that he saw many users misusing QThread by sub-classing it, adding some
slots to that subclass and doing something like this in the constructor:</p>

<pre class="brush: cpp">
 moveToThread(this);
</pre>

<p>They move a thread to itself. As Brad mentions, it is wrong: the QThread is supposed to
be the interface to manage the thread. So it is supposed to be used from the creating thread.</p>
<p>Slots in the QThread object are then not run in that thread and having slots in a subclass of QThread
is a bad practice.</p>

<p>
But then Brad continues and discourages any sub-classing of QThread at all.
He claims it is against proper object-oriented design.
This is where I disagree. Putting code in <code>run()</code> is a valid object-oriented way to extend a QThread:
A QThread represents a thread that just starts an event loop, a subclass represents a thread
that is extended to do what's in <code>run()</code>.
</p>

<p>After Brad's post, some members of the community went on a crusade against sub-classing QThread.
The problem is that there are many perfectly valid reasons to subclass QThread.</p>

<p>With Qt 5.0 and Qt 4.8.4, the documentation of QThread was changed so the sample code does not involve
sub-classing.
Look at the <a href="http://qt-project.org/doc/qt-4.8/QThread.html">first code sample
of the Qt 4.8 QThread documentation</a>.
It has many lines of boiler plate just to run some code in a thread. And the there is even
a leak: the QThread is never going to quit and be destroyed.
</p>

<p>I was asked on IRC a question from an user who followed that example in order
to run some simple code in a thread. He had a hard time to figure out how to properly
destroy the thread. That is what motivated me to write this blog entry.
</p>

<p>If you allow to subclass QThread, this is what you got:</p>


<pre class="code"><b>class</b> <dfn class="type" id="WorkerThread" title='WorkerThread' data-ref="WorkerThread" >WorkerThread</dfn> : <b>public</b> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qthread.h.html#QThread" title='QThread' data-ref="QThread" data-proj="qtbase" >QThread</a> {
    <em>void</em> <dfn class="virtual decl" id="_ZN12WorkerThread3runEv" title='WorkerThread::run' data-ref="_ZN12WorkerThread3runEv" >run</dfn>() {
        <i>// ...</i>
    }
};

<em>void</em> <span class="type" title='MyObject' data-ref="MyObject" >MyObject</span>::<dfn class="decl" id="_ZN8MyObject18startWorkInAThreadEv" title='MyObject::startWorkInAThread' data-ref="_ZN8MyObject18startWorkInAThreadEv" >startWorkInAThread</dfn>()
{
    <span class="type" title='WorkerThread' data-ref="WorkerThread" >WorkerThread</span> *<dfn class="local col1 ref" id="1workerThread" title='workerThread' data-type='WorkerThread *' data-ref="1workerThread" >workerThread</dfn> = <b>new</b> <span class="type" title='WorkerThread' data-ref="WorkerThread" >WorkerThread</span>;
    <a class="member" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#_ZN7QObject7connectEPKS_PKcS1_S3_N2Qt14ConnectionTypeE" title='QObject::connect' data-ref="_ZN7QObject7connectEPKS_PKcS1_S3_N2Qt14ConnectionTypeE" data-proj="qtbase" >connect</a>(<span class="local col1 ref" title='workerThread' data-ref="1workerThread" >workerThread</span>, <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#218" title="qFlagLocation(&quot;2&quot;&quot;finished()&quot; &quot;\0&quot; &quot;/home/olivier/woboq/web/woboqwebsite/data/blogs/qthread-you-were-not-doing-so-wrong.data/sample.cpp&quot; &quot;:&quot; &quot;16&quot;)">SIGNAL</a>(finished()),
            <span class="local col1 ref" title='workerThread' data-ref="1workerThread" >workerThread</span>, <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#217" title="qFlagLocation(&quot;1&quot;&quot;deleteLater()&quot; &quot;\0&quot; &quot;/home/olivier/woboq/web/woboqwebsite/data/blogs/qthread-you-were-not-doing-so-wrong.data/sample.cpp&quot; &quot;:&quot; &quot;17&quot;)">SLOT</a>(deleteLater()));
    <span class="local col1 ref" title='workerThread' data-ref="1workerThread" >workerThread</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qthread.h.html#_ZN7QThread5startENS_8PriorityE" title='QThread::start' data-ref="_ZN7QThread5startENS_8PriorityE" data-proj="qtbase" >start</a>();
}
</pre>

<p>This code does no longer leak and is much simpler and has less
overhead as it does not create useless object.</p>

<p>The Qt threading example
<a href="http://code.woboq.org/qt5/qtbase/examples/network/threadedfortuneserver/fortunethread.cpp.html#_ZN13FortuneThread3runEv">threadedfortuneserver</a>
is an example that uses this pattern to run blocking operations and is much simpler than
the equivalent using a worker object.</p>

<p>I have submitted a <a href="https://codereview.qt-project.org/45271">patch to the documentation</a>
to not discourage sub-classing QThread anymore.
</p>

<h2>Rules of thumbs</h2>
<p><b>When to subclass and when not to?</b></p>
<ul><li>If you do not really need an event loop in
   the thread, you should subclass.</li>
   <li>If you need an event loop and handle signals and slots
   within the thread, you may not need to subclass.</li>
   </ul>

<h2>What about using QtConcurrent instead?</h2>
<p>QThread is a quite low level and you should better use a higher level
API such as QtConcurrent. </p>
<p>Now, QtConcurrent has its own set of problems: It is tied to a single thread pool so it is not
a good solution if you want to run blocking operations. It has also some problems in its
implementation that gives some performance overhead. All of this is fixable.
Perhaps even Qt 5.1 will see some improvements.</p>

<p>A good alternative is also the <a href="http://woboq.com/blog/cpp11-in-qt5.html">C++11</a> standard library with
<code><a href="http://en.cppreference.com/w/cpp/thread/thread/thread">std::thread</a></code>
and <code><a href="http://en.cppreference.com/w/cpp/thread/async">std::async</a></code> which are
now the standard way to run code in a thread. And the good news is that it still works fine with Qt:
All other Qt threading primitives can be used with native threads.
(Qt will create automatically create a QThread if required).
</p>

]]></description></item>
<item><title>How Qt Signals and Slots Work - Part 2 - Qt5 New Syntax</title><link>http://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html</link><pubDate>Mon, 17 Dec 2012 18:16:00 GMT</pubDate><description><![CDATA[


<div class="intro">
<p>This is the sequel of my <a href="http://woboq.com/blog/how-qt-signals-slots-work.html">
previous article</a> explaining the implementation details of the signals and slots.
In the <a href="http://woboq.com/blog/how-qt-signals-slots-work.html">Part 1</a>, we have seen
the general principle and how it works with the old syntax.
In this blog post, we will see the implementation details behind the
new <a href="http://woboq.com/blog/new-signals-slots-syntax-in-qt5.html">function pointer
based syntax in Qt5</a>.</p>

</div>

<h2>New Syntax in Qt5</h2>
<p>
   The new syntax looks like this:</p>

<pre class="code">  <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a>::<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#_ZN7QObject7connectEPKN9QtPrivate15FunctionPointerIT_E6ObjectES2_PKNS1_IT0_E6ObjectES7_N2Qt14ConnectionTypeE" title='QObject::connect' data-ref="_ZN7QObject7connectEPKN9QtPrivate15FunctionPointerIT_E6ObjectES2_PKNS1_IT0_E6ObjectES7_N2Qt14ConnectionTypeE" data-proj="qtbase" >connect</a>(&amp;<span class="local col3 ref" title='a' data-ref="3a" >a</span>, &amp;<span class="type" title='Counter' data-ref="Counter" >Counter</span>::<span class="ref" title='Counter::valueChanged' data-ref="_ZN7Counter12valueChangedEi" >valueChanged</span>,
                   &amp;<span class="local col4 ref" title='b' data-ref="4b" >b</span>, &amp;<span class="type" title='Counter' data-ref="Counter" >Counter</span>::<span class="ref" title='Counter::setValue' data-ref="_ZN7Counter8setValueEi" >setValue</span>);
</pre>


<h3>Why the new syntax?</h3>

<p>
I already explained the advantages of the new syntax in a
<a href="http://woboq.com/blog/new-signals-slots-syntax-in-qt5.html">dedicated blog entry.</a>
To summarize, the new syntax allows compile-time checking of the signals and slots. It also allows
automatic conversion of the arguments if they do not have the same types.
As a bonus, it enables the support for lambda expressions.</p>

<h2>New overloads</h2>

<p>There was only a few changes required to make that possible.<br/>
The main idea is to have new overloads to <code>QObject::connect</code> which take the pointers
to functions as arguments instead of <code>char*</code>
</p>

<p>There are three new static overloads of <code>QObject::connect</code>:  (not actual code)</p>
<ol><li>
<pre>QObject::connect(const QObject *<var>sender</var>, <u>PointerToMemberFunction</u> <var>signal</var>,
                 const QObject *<var>receiver</var>, <u>PointerToMemberFunction</u> <var>slot</var>,
                 Qt::ConnectionType <var>type</var>)</pre></li>

<li>
<pre>QObject::connect(const QObject *<var>sender</var>, <u>PointerToMemberFunction</u> <var>signal</var>,
                 <u>PointerToFunction</u> <var>method</var>)</pre></li>
<li><pre>QObject::connect(const QObject *<var>sender</var>, <u>PointerToMemberFunction</u> <var>signal</var>,
                 <u>Functor</u> <var>method</var>)</pre></li>
                    </ol>

<p>The first one is the one that is much closer to the old syntax: you connect a signal from the sender
to a slot in a receiver object.
The two other overloads are connecting a signal to a static function or a functor object without
a receiver.</p>

<p>They are very similar and we will only analyze the first one in this article.</p>

<h2>Pointer to Member Functions</h2>

<p>Before continuing my explanation, I would like to open a parenthesis to
talk a bit about pointers to member functions.</p>

<p>Here is a simple sample code that declares a pointer to member function and calls it.</p>

<pre class="code">  <em>void</em> (QPoint::*<dfn class="local col1 ref" id="1myFunctionPtr" title='myFunctionPtr' data-type='void (QPoint::*)(int)' data-ref="1myFunctionPtr" >myFunctionPtr</dfn>)(<em>int</em>); <i>// Declares myFunctionPtr as a pointer to</i>
                                      <i>// a member function returning void and</i>
<i>                                      // taking (int) as parameter</i>
  <span class="local col1 ref" title='myFunctionPtr' data-ref="1myFunctionPtr" >myFunctionPtr</span> = &amp;<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qpoint.h.html#QPoint" title='QPoint' data-ref="QPoint" data-proj="qtbase" >QPoint</a>::<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qpoint.h.html#_ZN6QPoint4setXEi" title='QPoint::setX' data-ref="_ZN6QPoint4setXEi" data-proj="qtbase" >setX</a>;
  <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qpoint.h.html#QPoint" title='QPoint' data-ref="QPoint" data-proj="qtbase" >QPoint</a> <dfn class="local col2 ref" id="2p" title='p' data-type='QPoint' data-ref="2p" >p</dfn>;
  <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qpoint.h.html#QPoint" title='QPoint' data-ref="QPoint" data-proj="qtbase" >QPoint</a> *<dfn class="local col3 ref" id="3pp" title='pp' data-type='QPoint *' data-ref="3pp" >pp</dfn> = &amp;<span class="local col2 ref" title='p' data-ref="2p" >p</span>;
  (<span class="local col2 ref" title='p' data-ref="2p" >p</span>.*<span class="local col1 ref" title='myFunctionPtr' data-ref="1myFunctionPtr" >myFunctionPtr</span>)(<var>5</var>); <i>// calls p.setX(5);</i>
  (<span class="local col3 ref" title='pp' data-ref="3pp" >pp</span>-&gt;*<span class="local col1 ref" title='myFunctionPtr' data-ref="1myFunctionPtr" >myFunctionPtr</span>)(<var>5</var>); <i>// calls pp-&gt;setX(5);</i>
</pre>

<p>Pointers to member and pointers to member functions
  are usually part of the subset of C++ that is not much used and thus lesser known.
<br/>
 The good news is that you still do not really need to know much about them
   to use Qt and its new syntax. All you need to remember is to put the
   <code>&amp;</code> before the name of the signal in your connect call.
   But you will not need to cope with the <code>::*</code>, <code>.*</code>
   or <code>->*</code> cryptic operators.</p>
<p>These cryptic operators allow you to declare a pointer to a member or access it.
The type of such pointers includes the return type, the class which owns the member, the types of each argument
and the const-ness of the function.</p>

<p>You cannot really convert pointer to member functions to anything and in particular not to
<code>void*</code> because they have a different <code>sizeof</code>.<br/>

If the function varies slightly in signature, you cannot convert from one to the other.
For example, even converting from <code>void (MyClass::*)(int) const</code> to
<code>void (MyClass::*)(int)</code> is not allowed.
(You could do it with reinterpret_cast; but that would be an undefined behaviour if you call
them, according to the standard)
</p>

<p>Pointer to member functions are not just like normal function pointers.
A normal function pointer is just a normal pointer the address where the
code of that function lies.
But pointer to member function need to store more information:
member functions can be virtual and there is also an offset to apply to the
hidden <code>this</code> in case of multiple inheritance.<br/>
<code>sizeof</code> of a pointer to a member function can even
<a href="http://blogs.msdn.com/b/oldnewthing/archive/2004/02/09/70002.aspx">
vary depending of the class</a>.
This is why we need to take special care when manipulating them.</p>

<h2>Type Traits: <code>QtPrivate::FunctionPointer</code></h2>

<p>Let me introduce you to the <code>QtPrivate::FunctionPointer</code> type trait.<br/>
A trait is basically a helper class that gives meta data about a given type.
Another example of trait in Qt is
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qtypeinfo.h.html#QTypeInfo">QTypeInfo</a>.
</p>

<p>What we will need to know in order to implement the new syntax is information about a function pointer.</p>
<p>The <code>template&lt;typename T&gt; struct FunctionPointer</code> will give us information
about T via its member.</p>
<ul>
<li>
    <b><code>ArgumentCount</code>:</b>  An integer representing the number of arguments of the function.
</li>
<li>
    <b><code>Object</code>:</b> Exists only for pointer to member function. It is a typedef to the class of which the
      function is a member.
</li>
<li>
    <b><code>Arguments</code>:</b> Represents the list of argument. It is a typedef to a meta-programming list.
</li>
<li>
   <b><code>call(T &amp;function, QObject *receiver, void **args)</code>:</b>
   A static function that will call the function, applying the given parameters.
</li>
</ul>

<p>Qt still supports C++98 compiler which means we unfortunately cannot require support for variadic templates.
Therefore we had to specialize our trait function for each number of arguments.
We have four kinds of specializationd: normal function pointer, pointer to member function,
pointer to const member function and functors.
For each kind, we need to specialize for each number of arguments. We support up to six arguments.
We also made a specialization using variadic template
so we support arbitrary number of arguments if the compiler supports variadic templates.
</p>

<p>The implementation of <code>FunctionPointer</code> lies in
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::FunctionPointer">
qobjectdefs_impl.h</a>.</p>


<h2><code>QObject::connect</code></h2>

<p>The implementation relies on a lot of template code. I  am not going to explain all of it.</p>

<p>Here is the code of the first new overload from
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#_ZN7QObject7connectEPKN9QtPrivate15FunctionPointerIT_E6ObjectES2_PKNS1_IT0_E6ObjectES7_N2Qt14ConnectionTypeE">
qobject.h</a>:</p>

<pre class="code">
<b>template</b> &lt;<b>typename</b> Func1, <b>typename</b> Func2&gt;
<em>static</em> <b>inline</b> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject::Connection" title='QMetaObject::Connection' data-ref="QMetaObject::Connection" data-proj="qtbase" >Connection</a> <dfn class="decl" id="_ZN8QObject_7connectEPKN9QtPrivate15FunctionPointerIT_E6ObjectES2_PKNS1_IT0_E6ObjectES7_N2Qt14ConnectionTypeE" title='QObject_::connect' data-ref="_ZN8QObject_7connectEPKN9QtPrivate15FunctionPointerIT_E6ObjectES2_PKNS1_IT0_E6ObjectES7_N2Qt14ConnectionTypeE" >connect</dfn>(
    <em>const</em> <b>typename</b> <span class="namespace">QtPrivate::</span><a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::FunctionPointer" title='QtPrivate::FunctionPointer' data-ref="QtPrivate::FunctionPointer" data-proj="qtbase" >FunctionPointer</a>&lt;Func1&gt;::Object *<dfn class="local col1 ref" id="1sender" title='sender' data-type='const typename QtPrivate::FunctionPointer&lt;Func1&gt;::Object *' data-ref="1sender" >sender</dfn>, Func1 <dfn class="local col2 ref" id="2signal" title='signal' data-type='Func1' data-ref="2signal" >signal</dfn>,
    <em>const</em> <b>typename</b> <span class="namespace">QtPrivate::</span><a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::FunctionPointer" title='QtPrivate::FunctionPointer' data-ref="QtPrivate::FunctionPointer" data-proj="qtbase" >FunctionPointer</a>&lt;Func2&gt;::Object *<dfn class="local col3 ref" id="3receiver" title='receiver' data-type='const typename QtPrivate::FunctionPointer&lt;Func2&gt;::Object *' data-ref="3receiver" >receiver</dfn>, Func2 <dfn class="local col4 ref" id="4slot" title='slot' data-type='Func2' data-ref="4slot" >slot</dfn>,
    <span class="namespace">Qt::</span><a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qnamespace.h.html#Qt::ConnectionType" title='Qt::ConnectionType' data-ref="Qt::ConnectionType" data-proj="qtbase" >ConnectionType</a> <dfn class="local col5 ref" id="5type" title='type' data-type='Qt::ConnectionType' data-ref="5type" >type</dfn> = <span class="namespace">Qt::</span><a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qnamespace.h.html#Qt::ConnectionType::AutoConnection" title='Qt::ConnectionType::AutoConnection' data-ref="Qt::ConnectionType::AutoConnection" data-proj="qtbase" >AutoConnection</a>)
{
  <b>typedef</b> <span class="namespace">QtPrivate::</span><a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::FunctionPointer" title='QtPrivate::FunctionPointer' data-ref="QtPrivate::FunctionPointer" data-proj="qtbase" >FunctionPointer</a>&lt;Func1&gt; <dfn class="local col6 typedef" id="6SignalType" title='SignalType' data-type='QtPrivate::FunctionPointer&lt;Func1&gt;' data-ref="6SignalType" >SignalType</dfn>;
  <b>typedef</b> <span class="namespace">QtPrivate::</span><a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::FunctionPointer" title='QtPrivate::FunctionPointer' data-ref="QtPrivate::FunctionPointer" data-proj="qtbase" >FunctionPointer</a>&lt;Func2&gt; <dfn class="local col7 typedef" id="7SlotType" title='SlotType' data-type='QtPrivate::FunctionPointer&lt;Func2&gt;' data-ref="7SlotType" >SlotType</dfn>;

  <i>//compilation error if the arguments does not match.</i>
  <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qglobal.h.html#643" title="static_assert(bool(int(SignalType::ArgumentCount) &gt;= int(SlotType::ArgumentCount)), &quot;The slot requires more arguments than the signal provides.&quot;)">Q_STATIC_ASSERT_X</a>(<em>int</em>(<span class="local col6 typedef" title='SignalType' data-ref="6SignalType" >SignalType</span>::ArgumentCount) &gt;= <em>int</em>(<span class="local col7 typedef" title='SlotType' data-ref="7SlotType" >SlotType</span>::ArgumentCount),
                    <q>"The slot requires more arguments than the signal provides."</q>);
  <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qglobal.h.html#643" title="static_assert(bool((QtPrivate::CheckCompatibleArguments&lt;typename SignalType::Arguments, typename SlotType::Arguments&gt;::value)), &quot;Signal and slot arguments are not compatible.&quot;)">Q_STATIC_ASSERT_X</a>((QtPrivate::<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::CheckCompatibleArguments" title='QtPrivate::CheckCompatibleArguments' data-ref="QtPrivate::CheckCompatibleArguments" data-proj="qtbase" >CheckCompatibleArguments</a>&lt;<b>typename</b> <span class="local col6 typedef" title='SignalType' data-ref="6SignalType" >SignalType</span>::Arguments,
                                                         <b>typename</b> <span class="local col7 typedef" title='SlotType' data-ref="7SlotType" >SlotType</span>::Arguments&gt;::value),
                    <q>"Signal and slot arguments are not compatible."</q>);
  <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qglobal.h.html#643" title="static_assert(bool((QtPrivate::AreArgumentsCompatible&lt;typename SlotType::ReturnType, typename SignalType::ReturnType&gt;::value)), &quot;Return type of the slot is not compatible with the return type of the signal.&quot;)">Q_STATIC_ASSERT_X</a>((QtPrivate::<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::AreArgumentsCompatible" title='QtPrivate::AreArgumentsCompatible' data-ref="QtPrivate::AreArgumentsCompatible" data-proj="qtbase" >AreArgumentsCompatible</a>&lt;<b>typename</b> <span class="local col7 typedef" title='SlotType' data-ref="7SlotType" >SlotType</span>::ReturnType,
                                                       <b>typename</b> <span class="local col6 typedef" title='SignalType' data-ref="6SignalType" >SignalType</span>::ReturnType&gt;::value),
                    <q>"Return type of the slot is not compatible with the return type of the signal."</q>);

  <em>const</em> <em>int</em> *<dfn class="local col8 ref" id="8types" title='types' data-type='const int *' data-ref="8types" >types</dfn>;
  <i>/* ... Skipped initialization of types, used for QueuedConnection ...*/</i>

  <span class="namespace">QtPrivate::</span><a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_impl.h.html#QtPrivate::QSlotObjectBase" title='QtPrivate::QSlotObjectBase' data-ref="QtPrivate::QSlotObjectBase" data-proj="qtbase" >QSlotObjectBase</a> *<dfn class="local col9 ref" id="9slotObj" title='slotObj' data-type='QtPrivate::QSlotObjectBase *' data-ref="9slotObj" >slotObj</dfn> = <b>new</b> <span class="namespace">QtPrivate::</span><a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_impl.h.html#QtPrivate::QSlotObject" title='QtPrivate::QSlotObject' data-ref="QtPrivate::QSlotObject" data-proj="qtbase" >QSlotObject</a>&lt;Func2,
        <b>typename</b> <span class="namespace">QtPrivate::</span><a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::List_Left" title='QtPrivate::List_Left' data-ref="QtPrivate::List_Left" data-proj="qtbase" >List_Left</a>&lt;<b>typename</b> <span class="local col6 typedef" title='SignalType' data-ref="6SignalType" >SignalType</span>::Arguments, <span class="local col7 typedef" title='SlotType' data-ref="7SlotType" >SlotType</span>::ArgumentCount&gt;::Value,
        <b>typename</b> <span class="local col6 typedef" title='SignalType' data-ref="6SignalType" >SignalType</span>::ReturnType&gt;(<span class="local col4 ref" title='slot' data-ref="4slot" >slot</span>);


  <b>return</b> <a class="member" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#_ZN7QObject11connectImplEPKS_PPvS1_S3_PN9QtPrivate15QSlotObjectBaseEN2Qt14ConnectionTypeEPKiPK11QMetaObject" title='QObject::connectImpl' data-ref="_ZN7QObject11connectImplEPKS_PPvS1_S3_PN9QtPrivate15QSlotObjectBaseEN2Qt14ConnectionTypeEPKiPK11QMetaObject" data-proj="qtbase" >connectImpl</a>(<span class="local col1 ref" title='sender' data-ref="1sender" >sender</span>, <b>reinterpret_cast</b>&lt;<em>void</em> **&gt;(&amp;<span class="local col2 ref" title='signal' data-ref="2signal" >signal</span>),
                     <span class="local col3 ref" title='receiver' data-ref="3receiver" >receiver</span>, <b>reinterpret_cast</b>&lt;<em>void</em> **&gt;(&amp;<span class="local col4 ref" title='slot' data-ref="4slot" >slot</span>), <span class="local col9 ref" title='slotObj' data-ref="9slotObj" >slotObj</span>,
                     <span class="local col5 ref" title='type' data-ref="5type" >type</span>, <span class="local col8 ref" title='types' data-ref="8types" >types</span>, &amp;<span class="local col6 typedef" title='SignalType' data-ref="6SignalType" >SignalType</span>::Object::staticMetaObject);
}
</pre>

<p>You notice in the function signature that <code>sender</code> and <code>receiver</code>
are not just <code>QObject*</code> as the documentation points out. They are pointers to
<code>typename FunctionPointer::Object</code> instead.
This uses <a href="http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error">SFINAE</a>
to make this overload only enabled for pointers to member functions
because the <code>Object</code> only exists in <code>FunctionPointer</code> if
the type is a pointer to member function. 
</p>

<p>We then start with a bunch of
<a href="http://woboq.com/blog/cpp11-in-qt5.html#static_assert"><code>Q_STATIC_ASSERT</code></a>.

They should generate sensible compilation error messages when the user made a mistake.
If the user did something wrong, it is important that he/she sees an error here
and not in the soup of template code in the <code>_impl.h</code> files.
We want to hide the underlying implementation from the user who should not need
to care about it.<br/>

That means that if you ever you see a confusing error in the implementation details,
it should be considered as a bug that <a href="https://bugreports.qt-project.org/">should be reported</a>.
</p>

<p>We then allocate a <code>QSlotObject</code> that is going to be passed to <code>connectImpl()</code>.
The <code>QSlotObject</code> is a wrapper around the slot that will help calling it. It also
knows the type of the signal arguments so it can do the proper type conversion.<br/>
We use <code>List_Left</code> to only pass the same number as argument as the slot, which allows connecting
a signal with many arguments to a slot with less arguments.
</p>

<p><code>QObject::connectImpl</code> is the private internal function
that will perform the connection.
It is similar to the original syntax, the difference is that instead of storing a
method index in the <code>QObjectPrivate::Connection</code> structure,
we store a pointer to the <code>QSlotObjectBase</code>.</p>
<p>
The reason why we pass <code>&amp;slot</code> as a <code>void**</code> is only to
be able to compare it if the type is <code>Qt::UniqueConnection</code>.
</p>

<p>We also pass the <code>&amp;signal</code> as a <code>void**</code>.
It is a pointer to the member function pointer. (Yes, a pointer to the pointer)
</p>


<h2>Signal Index</h2>

<p>We need to make a relationship between the signal pointer and the signal index.<br/>
We use MOC for that. Yes, that means this new syntax
is still using the MOC and that there are no plans to get rid of it :-).</p>

<p>MOC will generate code in <code>qt_static_metacall</code>
that compares the parameter and returns the right index.
<code>connectImpl</code> will call the <code>qt_static_metacall</code> function with the
pointer to the function pointer.</p>

<pre class="code"><em>void</em> <span class="type" title='Counter' data-ref="Counter" >Counter</span>::<dfn class="decl" id="_ZN7Counter18qt_static_metacallEP7QObjectN11QMetaObject4CallEiPPv" title='Counter::qt_static_metacall' data-ref="_ZN7Counter18qt_static_metacallEP7QObjectN11QMetaObject4CallEiPPv" >qt_static_metacall</dfn>(<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a> *<dfn class="local col5 ref" id="5_o" title='_o' data-type='QObject *' data-ref="5_o" >_o</dfn>, <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject::Call" title='QMetaObject::Call' data-ref="QMetaObject::Call" data-proj="qtbase" >Call</a> <dfn class="local col6 ref" id="6_c" title='_c' data-type='QMetaObject::Call' data-ref="6_c" >_c</dfn>, <em>int</em> <dfn class="local col7 ref" id="7_id" title='_id' data-type='int' data-ref="7_id" >_id</dfn>, <em>void</em> **<dfn class="local col8 ref" id="8_a" title='_a' data-type='void **' data-ref="8_a" >_a</dfn>)
{
    <b>if</b> (<span class="local col6 ref" title='_c' data-ref="6_c" >_c</span> == <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject::Call::InvokeMetaMethod" title='QMetaObject::Call::InvokeMetaMethod' data-ref="QMetaObject::Call::InvokeMetaMethod" data-proj="qtbase" >InvokeMetaMethod</a>) {
<i>        /* .... skipped ....*/</i>
    } <b>else</b> <b>if</b> (<span class="local col6 ref" title='_c' data-ref="6_c" >_c</span> == <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject::Call::IndexOfMethod" title='QMetaObject::Call::IndexOfMethod' data-ref="QMetaObject::Call::IndexOfMethod" data-proj="qtbase" >IndexOfMethod</a>) {
        <em>int</em> *<dfn class="local col1 ref" id="11result" title='result' data-type='int *' data-ref="11result" >result</dfn> = <b>reinterpret_cast</b>&lt;<em>int</em> *&gt;(<span class="local col8 ref" title='_a' data-ref="8_a" >_a</span>[<var>0</var>]);
        <em>void</em> **<dfn class="local col2 ref" id="12func" title='func' data-type='void **' data-ref="12func" >func</dfn> = <b>reinterpret_cast</b>&lt;<em>void</em> **&gt;(<span class="local col8 ref" title='_a' data-ref="8_a" >_a</span>[<var>1</var>]);
        {
            <b>typedef</b> <em>void</em> (Counter::*<dfn class="local col3 typedef" id="13_t" title='_t' data-type='void (Counter::*)(int)' data-ref="13_t" >_t</dfn>)(<em>int</em> );
            <b>if</b> (*<b>reinterpret_cast</b>&lt;<span class="local col3 typedef" title='_t' data-ref="13_t" >_t</span> *&gt;(<span class="local col2 ref" title='func' data-ref="12func" >func</span>) == <b>static_cast</b>&lt;<span class="local col3 typedef" title='_t' data-ref="13_t" >_t</span>&gt;(&amp;<span class="type" title='Counter' data-ref="Counter" >Counter</span>::<span class="member" title='Counter::valueChanged' data-ref="_ZN7Counter12valueChangedEi" >valueChanged</span>)) {
                *<span class="local col1 ref" title='result' data-ref="11result" >result</span> = <var>0</var>;
            }
        }
        {
            <b>typedef</b> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qstring.h.html#QString" title='QString' data-ref="QString" data-proj="qtbase" >QString</a> (Counter::*<dfn class="local col4 typedef" id="14_t" title='_t' data-type='QString (Counter::*)(const QString &amp;)' data-ref="14_t" >_t</dfn>)(<em>const</em> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qstring.h.html#QString" title='QString' data-ref="QString" data-proj="qtbase" >QString</a> &amp; );
            <b>if</b> (*<b>reinterpret_cast</b>&lt;<span class="local col4 typedef" title='_t' data-ref="14_t" >_t</span> *&gt;(<span class="local col2 ref" title='func' data-ref="12func" >func</span>) == <b>static_cast</b>&lt;<span class="local col4 typedef" title='_t' data-ref="14_t" >_t</span>&gt;(&amp;<span class="type" title='Counter' data-ref="Counter" >Counter</span>::<span class="member" title='Counter::someOtherSignal' data-ref="_ZN7Counter15someOtherSignalERK7QString" >someOtherSignal</span>)) {
                *<span class="local col1 ref" title='result' data-ref="11result" >result</span> = <var>1</var>;
            }
        }
        {
            <b>typedef</b> <em>void</em> (Counter::*<dfn class="local col5 typedef" id="15_t" title='_t' data-type='void (Counter::*)()' data-ref="15_t" >_t</dfn>)();
            <b>if</b> (*<b>reinterpret_cast</b>&lt;<span class="local col5 typedef" title='_t' data-ref="15_t" >_t</span> *&gt;(<span class="local col2 ref" title='func' data-ref="12func" >func</span>) == <b>static_cast</b>&lt;<span class="local col5 typedef" title='_t' data-ref="15_t" >_t</span>&gt;(&amp;<span class="type" title='Counter' data-ref="Counter" >Counter</span>::<span class="member" title='Counter::anotherSignal' data-ref="_ZN7Counter13anotherSignalEv" >anotherSignal</span>)) {
                *<span class="local col1 ref" title='result' data-ref="11result" >result</span> = <var>2</var>;
            }
        }
    }
}

</pre>

<p>Once we have the signal index, we can proceed like in the other syntax.</p>

<h2>The QSlotObjectBase</h2>

<p><code>QSlotObjectBase</code> is the object passed to <code>connectImpl</code>
that represents the slot.</p>

<p>Before showing the real code, this is what QObject::QSlotObjectBase
was in Qt5 alpha:</p>

<pre class="code"><b>struct</b> <dfn class="type" id="QSlotObjectBase" title='QSlotObjectBase' data-ref="QSlotObjectBase" >QSlotObjectBase</dfn> {
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qatomic.h.html#QAtomicInt" title='QAtomicInt' data-ref="QAtomicInt" data-proj="qtbase" >QAtomicInt</a> <dfn class="decl" id="QSlotObjectBase::ref" title='QSlotObjectBase::ref' data-ref="QSlotObjectBase::ref" >ref</dfn>;
    <dfn class="decl" id="_ZN15QSlotObjectBaseC1Ev" title='QSlotObjectBase::QSlotObjectBase' data-ref="_ZN15QSlotObjectBaseC1Ev" >QSlotObjectBase</dfn>() : <span class="member" title='QSlotObjectBase::ref' data-ref="QSlotObjectBase::ref" >ref</span>(<var>1</var>) {}
    <b>virtual</b> <dfn class="virtual decl" id="_ZN15QSlotObjectBaseD1Ev" title='QSlotObjectBase::~QSlotObjectBase' data-ref="_ZN15QSlotObjectBaseD1Ev" >~</dfn>QSlotObjectBase();
    <b>virtual</b> <em>void</em> <dfn class="virtual decl" id="_ZN15QSlotObjectBase4callEP7QObjectPPv" title='QSlotObjectBase::call' data-ref="_ZN15QSlotObjectBase4callEP7QObjectPPv" >call</dfn>(<span class="type" title='QObject' data-ref="QObject" >QObject</span> *<dfn class="local col1 ref" id="1receiver" title='receiver' data-type='QObject *' data-ref="1receiver" >receiver</dfn>, <em>void</em> **<dfn class="local col2 ref" id="2a" title='a' data-type='void **' data-ref="2a" >a</dfn>) = <var>0</var>;
    <b>virtual</b> <em>bool</em> <dfn class="virtual decl" id="_ZN15QSlotObjectBase7compareEPPv" title='QSlotObjectBase::compare' data-ref="_ZN15QSlotObjectBase7compareEPPv" >compare</dfn>(<em>void</em> **) { <b>return</b> <b>false</b>; }
};
</pre>

<p>It is basically an interface that is meant to be re-implemented by
template classes implementing the call and comparison of the
function pointers.
</p>
<p>It is re-implemented by one of the <code>QSlotObject</code>, <code>QStaticSlotObject</code> or
<code>QFunctorSlotObject</code> template class.</p>

<h3>Fake Virtual Table</h3>

<p>The problem with that is that each instantiation of those object 
would need to create a virtual table which contains not only pointer to virtual functions
but also lot of information we do not need such as
<a href="http://en.wikipedia.org/wiki/Run-time_type_information">RTTI</a>.
That would result in lot of superfluous data and relocation in the binaries.
</p>

<p>In order to avoid that, <code>QSlotObjectBase</code> was changed not to be a C++ polymorphic class.
Virtual functions are emulated by hand.</p>

<pre class="code"><b>class</b> <dfn class="type" id="QtPrivate::QSlotObjectBase" title='QtPrivate::QSlotObjectBase' data-ref="QtPrivate::QSlotObjectBase" >QSlotObjectBase</dfn> {
  <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qatomic.h.html#QAtomicInt" title='QAtomicInt' data-ref="QAtomicInt" data-proj="qtbase" >QAtomicInt</a> <dfn class="decl" id="QtPrivate::QSlotObjectBase::m_ref" title='QtPrivate::QSlotObjectBase::m_ref' data-ref="QtPrivate::QSlotObjectBase::m_ref" >m_ref</dfn>;
  <b>typedef</b> <em>void</em> (*<dfn class="typedef" id="QtPrivate::QSlotObjectBase::ImplFn" title='QtPrivate::QSlotObjectBase::ImplFn' data-ref="QtPrivate::QSlotObjectBase::ImplFn" >ImplFn</dfn>)(<em>int</em> <dfn class="ref" id="which" title='which' data-ref="which" >which</dfn>, <span class="type" title='QtPrivate::QSlotObjectBase' data-ref="QtPrivate::QSlotObjectBase" >QSlotObjectBase</span>* <dfn class="ref" id="this_" title='this_' data-ref="this_" >this_</dfn>,
                         <span class="type" title='QObject' data-ref="QObject" >QObject</span> *<dfn class="ref" id="receiver" title='receiver' data-ref="receiver" >receiver</dfn>, <em>void</em> **<dfn class="ref" id="args" title='args' data-ref="args" >args</dfn>, <em>bool</em> *<dfn class="ref" id="ret" title='ret' data-ref="ret" >ret</dfn>);
  <em>const</em> <span class="typedef" title='QtPrivate::QSlotObjectBase::ImplFn' data-ref="QtPrivate::QSlotObjectBase::ImplFn" >ImplFn</span> <dfn class="decl" id="QtPrivate::QSlotObjectBase::m_impl" title='QtPrivate::QSlotObjectBase::m_impl' data-ref="QtPrivate::QSlotObjectBase::m_impl" >m_impl</dfn>;
<b>protected</b>:
  <b>enum</b> <dfn class="type" id="QtPrivate::QSlotObjectBase::Operation" title='QtPrivate::QSlotObjectBase::Operation' data-ref="QtPrivate::QSlotObjectBase::Operation" >Operation</dfn> { <dfn class="enum" id="QtPrivate::QSlotObjectBase::Operation::Destroy" title='QtPrivate::QSlotObjectBase::Operation::Destroy' data-ref="QtPrivate::QSlotObjectBase::Operation::Destroy" >Destroy</dfn>, <dfn class="enum" id="QtPrivate::QSlotObjectBase::Operation::Call" title='QtPrivate::QSlotObjectBase::Operation::Call' data-ref="QtPrivate::QSlotObjectBase::Operation::Call" >Call</dfn>, <dfn class="enum" id="QtPrivate::QSlotObjectBase::Operation::Compare" title='QtPrivate::QSlotObjectBase::Operation::Compare' data-ref="QtPrivate::QSlotObjectBase::Operation::Compare" >Compare</dfn> };
<b>public</b>:
  <b>explicit</b> <dfn class="decl" id="_ZN9QtPrivate15QSlotObjectBaseC1EPFviPS0_P7QObjectPPvPbE" title='QtPrivate::QSlotObjectBase::QSlotObjectBase' data-ref="_ZN9QtPrivate15QSlotObjectBaseC1EPFviPS0_P7QObjectPPvPbE" >QSlotObjectBase</dfn>(<span class="typedef" title='QtPrivate::QSlotObjectBase::ImplFn' data-ref="QtPrivate::QSlotObjectBase::ImplFn" >ImplFn</span> <dfn class="local col3 ref" id="3fn" title='fn' data-type='ImplFn' data-ref="3fn" >fn</dfn>) : <span class="member" title='QtPrivate::QSlotObjectBase::m_ref' data-ref="QtPrivate::QSlotObjectBase::m_ref" >m_ref</span>(<var>1</var>), <span class="member" title='QtPrivate::QSlotObjectBase::m_impl' data-ref="QtPrivate::QSlotObjectBase::m_impl" >m_impl</span>(<span class="local col3 ref" title='fn' data-ref="3fn" >fn</span>) {}
  <b>inline</b> <em>int</em> <dfn class="decl" id="_ZN9QtPrivate15QSlotObjectBase3refEv" title='QtPrivate::QSlotObjectBase::ref' data-ref="_ZN9QtPrivate15QSlotObjectBase3refEv" >ref</dfn>() <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qcompilerdetection.h.html#764" title="noexcept">Q_DECL_NOTHROW</a> { <b>return</b> <span class="member" title='QtPrivate::QSlotObjectBase::m_ref' data-ref="QtPrivate::QSlotObjectBase::m_ref" >m_ref</span>.<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qbasicatomic.h.html#_ZN19QBasicAtomicInteger3refEv" title='QBasicAtomicInteger::ref' data-ref="_ZN19QBasicAtomicInteger3refEv" data-proj="qtbase" >ref</a>(); }
  <b>inline</b> <em>void</em> <dfn class="decl" id="_ZN9QtPrivate15QSlotObjectBase16destroyIfLastRefEv" title='QtPrivate::QSlotObjectBase::destroyIfLastRef' data-ref="_ZN9QtPrivate15QSlotObjectBase16destroyIfLastRefEv" >destroyIfLastRef</dfn>() <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qcompilerdetection.h.html#764" title="noexcept">Q_DECL_NOTHROW</a> {
    <b>if</b> (!<span class="member" title='QtPrivate::QSlotObjectBase::m_ref' data-ref="QtPrivate::QSlotObjectBase::m_ref" >m_ref</span>.<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qbasicatomic.h.html#_ZN19QBasicAtomicInteger5derefEv" title='QBasicAtomicInteger::deref' data-ref="_ZN19QBasicAtomicInteger5derefEv" data-proj="qtbase" >deref</a>()) <span class="member" title='QtPrivate::QSlotObjectBase::m_impl' data-ref="QtPrivate::QSlotObjectBase::m_impl" >m_impl</span>(<span class="enum" title='QtPrivate::QSlotObjectBase::Operation::Destroy' data-ref="QtPrivate::QSlotObjectBase::Operation::Destroy" >Destroy</span>, <b>this</b>, <var>0</var>, <var>0</var>, <var>0</var>);
  }

  <b>inline</b> <em>bool</em> <dfn class="decl" id="_ZN9QtPrivate15QSlotObjectBase7compareEPPv" title='QtPrivate::QSlotObjectBase::compare' data-ref="_ZN9QtPrivate15QSlotObjectBase7compareEPPv" >compare</dfn>(<em>void</em> **<dfn class="local col4 ref" id="4a" title='a' data-type='void **' data-ref="4a" >a</dfn>) { <em>bool</em> <dfn class="local col5 ref" id="5ret" title='ret' data-type='bool' data-ref="5ret" >ret</dfn>; <span class="member" title='QtPrivate::QSlotObjectBase::m_impl' data-ref="QtPrivate::QSlotObjectBase::m_impl" >m_impl</span>(<span class="enum" title='QtPrivate::QSlotObjectBase::Operation::Compare' data-ref="QtPrivate::QSlotObjectBase::Operation::Compare" >Compare</span>, <b>this</b>, <var>0</var>, <span class="local col4 ref" title='a' data-ref="4a" >a</span>, &amp;<span class="local col5 ref" title='ret' data-ref="5ret" >ret</span>); <b>return</b> <span class="local col5 ref" title='ret' data-ref="5ret" >ret</span>; }
  <b>inline</b> <em>void</em> <dfn class="decl" id="_ZN9QtPrivate15QSlotObjectBase4callEP7QObjectPPv" title='QtPrivate::QSlotObjectBase::call' data-ref="_ZN9QtPrivate15QSlotObjectBase4callEP7QObjectPPv" >call</dfn>(<span class="type" title='QObject' data-ref="QObject" >QObject</span> *<dfn class="local col6 ref" id="6r" title='r' data-type='QObject *' data-ref="6r" >r</dfn>, <em>void</em> **<dfn class="local col7 ref" id="7a" title='a' data-type='void **' data-ref="7a" >a</dfn>) {  <span class="member" title='QtPrivate::QSlotObjectBase::m_impl' data-ref="QtPrivate::QSlotObjectBase::m_impl" >m_impl</span>(<span class="enum" title='QtPrivate::QSlotObjectBase::Operation::Call' data-ref="QtPrivate::QSlotObjectBase::Operation::Call" >Call</span>,    <b>this</b>, <span class="local col6 ref" title='r' data-ref="6r" >r</span>, <span class="local col7 ref" title='a' data-ref="7a" >a</span>, <var>0</var>); }
};
</pre>

<p>The <code>m_impl</code> is a (normal) function pointer which performs
the three operations that were previously virtual functions. The "re-implementations"
set it to their own implementation in the constructor.</p>



<p>Please <b>do not</b> go in your code and replace all your virtual functions by such a
hack because you read here it was good.
This is only done in this case because almost every call to <code>connect</code>
would generate a new different type (since the QSlotObject has template parameters
wich depend on signature of the signal and the slot).</p>

<h2>Protected, Public, or Private Signals.</h2>

<p>Signals were <code>protected</code> in Qt4 and before. It was a design choice as signals should be emitted
<em>by</em> the object when its change its state. They should not be emitted from
outside the object and calling a signal on another object is almost always a bad idea.</p>

<p>However, with the new syntax, you need to be able take the <em>address</em>
of the signal from the point you make the connection.
The compiler would only let you do that if you have access to that signal.
Writing <code>&amp;Counter::valueChanged</code> would generate a compiler error
if the signal was not public.</p>

<p>In Qt 5 we had to change signals from <code>protected</code> to <code>public</code>.
This is unfortunate since this mean anyone can emit the signals.
We found no way around it. We tried a trick with the emit keyword. We tried returning a special value.
But nothing worked.
I believe that the advantages of the new syntax overcome the problem that signals are now public.
</p>

<p>Sometimes it is even desirable to have the signal private. This is the case for example in
<code>QAbstractItemModel</code>, where otherwise, developers tend to emit signal
from the derived class which is not what the API wants.
There used to be a pre-processor trick that made signals private
but it broke the new connection syntax.<br/>
A new hack has been introduced.
<code>QPrivateSignal</code> is a dummy (empty) struct declared private in the Q_OBJECT
macro. It can be used as the last parameter of the signal. Because it is private, only the object
has the right to construct it for calling the signal.
MOC will ignore the QPrivateSignal last argument while generating signature information.
See <a href="http://code.woboq.org/qt5/qtbase/src/corelib/itemmodels/qabstractitemmodel.h.html#_ZN18QAbstractItemModel21rowsAboutToBeInsertedERK11QModelIndexiiNS_14QPrivateSignalE">
qabstractitemmodel.h</a> for an example.
</p>


<h2>More Template Code</h2>

<p>The rest of the code is in
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html">
qobjectdefs_impl.h</a> and
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_impl.h.html">
qobject_impl.h</a>.

It is mostly standard dull template code.
</p>

<p>I will not go into much more details in this article,
but I will just go over few items that are worth mentioning.</p>

<h3>Meta-Programming List</h3>

<p>As pointed out earlier, <code>FunctionPointer::Arguments</code> is a <em>list</em>
of the arguments. The code needs to operate on that list:
iterate over each element, take only a part of it or select a given item.</p>
<p>That is why there is
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::List">
<code>QtPrivate::List</code></a> that can represent a list of types. Some helpers to operate on it are
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::List_Select">
<code>QtPrivate::List_Select</code></a> and
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::List_Left">
<code>QtPrivate::List_Left</code></a>, which give the N-th element in the list and a sub-list containing
the N first elements.</p>

<p>The implementation of <code>List</code> is different for compilers that support variadic templates and compilers that do not.</p>

<p>With variadic templates, it is a
<code>template&lt;typename... T&gt; struct List;</code>. The list of arguments is just encapsulated
in the template parameters.<br/>
For example: the type of a list containing the arguments <code>(int, QString, QObject*)</code> would simply be:
</p>
<pre>List&lt;int, QString, QObject *&gt;</pre>
<p>Without variadic template, it is a LISP-style list: <code>template&lt;typename Head, typename Tail &gt; struct List;</code>
where <code>Tail</code> can be either another <code>List</code> or <code>void</code> for the end of the list.<br/>
The same example as before would be:</p>
<pre>List&lt;int, List&lt;QString, List&lt;QObject *, void&gt; &gt; &gt;</pre>

<h3>ApplyReturnValue Trick</h3>

<p>In the function <code>FunctionPointer::call</code>, the <code>args[0]</code> is meant to receive the return value of the slot.
If the signal returns a value, it is a pointer to an object of the return type of
the signal, else, it is 0.
If the slot returns a value, we need to copy it in <code>arg[0]</code>. If it returns <code>void</code>, we do nothing.
</p>

<p>The problem is that it is not syntaxically correct to use the
return value of a function that returns <code>void</code>.
Should I have duplicated the already huge amount of code duplication: once for the void
return type and the other for the non-void?
No, thanks to the comma operator.
</p>

<p>In C++ you can do something like that:</p>

<pre class="code">
functionThatReturnsVoid(), somethingElse();
</pre>

<p>You could have replaced the comma by a semicolon and everything would have been fine.</p>

<p>Where it becomes interesting is when you call it with something that is not <code>void</code>:</p>

<pre class="code">
functionThatReturnsInt(), somethingElse();
</pre>

<p>
There, the comma will actually call an operator that you even can overload.
It is what we do in
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs_impl.h.html#QtPrivate::ApplyReturnValue">
qobjectdefs_impl.h</a>
</p>

<pre class="code"><b>template</b> &lt;<b>typename</b> T&gt;
<b>struct</b> <dfn class="type" id="QtPrivate::ApplyReturnValue" title='QtPrivate::ApplyReturnValue' data-ref="QtPrivate::ApplyReturnValue" >ApplyReturnValue</dfn> {
    <em>void</em> *<dfn class="decl" id="QtPrivate::ApplyReturnValue::data" title='QtPrivate::ApplyReturnValue::data' data-ref="QtPrivate::ApplyReturnValue::data" >data</dfn>;
    <dfn class="decl" id="_ZN9QtPrivate16ApplyReturnValueC1EPv" title='QtPrivate::ApplyReturnValue::ApplyReturnValue&lt;T&gt;' data-ref="_ZN9QtPrivate16ApplyReturnValueC1EPv" >ApplyReturnValue</dfn>(<em>void</em> *<dfn class="local col1 ref" id="1data_" title='data_' data-type='void *' data-ref="1data_" >data_</dfn>) : <span class="member" title='QtPrivate::ApplyReturnValue::data' data-ref="QtPrivate::ApplyReturnValue::data" >data</span>(<span class="local col1 ref" title='data_' data-ref="1data_" >data_</span>) {}
};

<b>template</b>&lt;<b>typename</b> T, <b>typename</b> U&gt;
<em>void</em> <dfn class="decl" id="_ZN9QtPrivatecmERKT_RKNS_16ApplyReturnValueIT0_EE" title='QtPrivate::operator,' data-ref="_ZN9QtPrivatecmERKT_RKNS_16ApplyReturnValueIT0_EE" ><b>operator</b>,</dfn>(<em>const</em> T &amp;<dfn class="local col2 ref" id="2value" title='value' data-type='const T &amp;' data-ref="2value" >value</dfn>, <em>const</em> <span class="type" title='QtPrivate::ApplyReturnValue' data-ref="QtPrivate::ApplyReturnValue" >ApplyReturnValue</span>&lt;U&gt; &amp;<dfn class="local col3 ref" id="3container" title='container' data-type='const ApplyReturnValue&lt;U&gt; &amp;' data-ref="3container" >container</dfn>) {
    <b>if</b> (<span class="local col3 ref" title='container' data-ref="3container" >container</span>.data)
        *<b>reinterpret_cast</b>&lt;U*&gt;(<span class="local col3 ref" title='container' data-ref="3container" >container</span>.data) = <span class="local col2 ref" title='value' data-ref="2value" >value</span>;
}
<b>template</b>&lt;<b>typename</b> T&gt;
<em>void</em> <dfn class="decl" id="_ZN9QtPrivatecmET_RKNS_16ApplyReturnValueIvEE" title='QtPrivate::operator,' data-ref="_ZN9QtPrivatecmET_RKNS_16ApplyReturnValueIvEE" ><b>operator</b>,</dfn>(T, <em>const</em> <span class="type" title='QtPrivate::ApplyReturnValue' data-ref="QtPrivate::ApplyReturnValue" >ApplyReturnValue</span>&lt;<em>void</em>&gt; &amp;) {}
</pre>

<p>ApplyReturnValue is just a wrapper around a <code>void*</code>. Then it can be used
in each helper. This is for example the case of a functor without arguments:</p>

<pre class="code">  <em>static</em> <em>void</em> <dfn class="decl" id="_ZN9QtPrivate7FunctorIT_Li0EE4callERS1_PvPS4_" title='QtPrivate::Functor&lt;type-parameter-0-0, 0&gt;::call' data-ref="_ZN9QtPrivate7FunctorIT_Li0EE4callERS1_PvPS4_" >call</dfn>(Function &amp;<dfn class="local col4 ref" id="4f" title='f' data-type='Function &amp;' data-ref="4f" >f</dfn>, <em>void</em> *, <em>void</em> **<dfn class="local col5 ref" id="5arg" title='arg' data-type='void **' data-ref="5arg" >arg</dfn>) {
      <span class="local col4 ref" title='f' data-ref="4f" >f</span>(), <span class="type" title='QtPrivate::ApplyReturnValue' data-ref="QtPrivate::ApplyReturnValue" >ApplyReturnValue</span>&lt;SignalReturnType&gt;(<span class="local col5 ref" title='arg' data-ref="5arg" >arg</span>[<var>0</var>]);
  }
</pre>


<p>This code is inlined, so it will not cost anything at run-time.</p>

<h2>Conclusion</h2>

<p>This is it for this blog post. There is still a lot to talk about
(I have not even mentioned QueuedConnection or thread safety yet), but I hope you found this
interresting and that you learned here something that might help you as a programmer.</p>


]]></description></item>
<item><title>How Qt Signals and Slots Work</title><link>http://woboq.com/blog/how-qt-signals-slots-work.html</link><pubDate>Sun, 02 Dec 2012 21:00:00 GMT</pubDate><description><![CDATA[


<div class="intro">
<p>Qt is well known for its signals and slots mechanism. But how does it work?
In this blog post, we will explore the internals of QObject and QMetaObject
and discover how signals and slot work under the hood.
</p>


<p>In this blog article, I show portions of Qt5 code,
sometimes edited for formatting and brevity.</p>


</div>



<h2>Signals and Slots</h2>

<p>First, let us recall how signals and slots look like by showing the
<a href="http://qt-project.org/doc/qt-4.8/signalsandslots.html">official example</a>.</p>

<div class="woboq_hidden">
If you read this article from the RSS, you may want to open it in its
<a href="http://woboq.com/blog/how-qt-signals-slots-work.html">original URL</a>
to have property formatted code.</div>
<div class="side_box">Hover over the code
to see fancy tool tips
powered by the
<a href="http://code.woboq.org/">Woboq Code Browser</a>!
</div>

<p>The header looks like this:</p>

<pre class="code"><b>class</b> <dfn class="type" id="Counter" title='Counter' data-ref="Counter" >Counter</dfn> : <b>public</b> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a>
{
    <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#148" title="public: template &lt;typename T&gt; inline void qt_check_for_QOBJECT_macro(const T &amp;_q_argument) const { int i = qYouForgotTheQ_OBJECT_Macro(this, &amp;_q_argument); i = i + 1; } static const QMetaObject staticMetaObject; virtual const QMetaObject *metaObject() const; virtual void *qt_metacast(const char *); static inline QString tr(const char *s, const char *c = 0, int n = -1) { return staticMetaObject.tr(s, c, n); } static inline QString trUtf8(const char *s, const char *c = 0, int n = -1) { return staticMetaObject.tr(s, c, n); } virtual int qt_metacall(QMetaObject::Call, int, void **); private: __attribute__((visibility(&quot;hidden&quot;))) static void qt_static_metacall(QObject *, QMetaObject::Call, int, void **); struct QPrivateSignal {};">Q_OBJECT</a>
    <em>int</em> <dfn class="decl" id="Counter::m_value" title='Counter::m_value' data-ref="Counter::m_value" >m_value</dfn>;
<b>public</b>:
    <em>int</em> <dfn class="decl" id="_ZNK7Counter5valueEv" title='Counter::value' data-ref="_ZNK7Counter5valueEv" >value</dfn>() <em>const</em> { <b>return</b> <span class="member" title='Counter::m_value' data-ref="Counter::m_value" >m_value</span>; }
<b>public</b> <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#73" title="">slots</a>:
    <em>void</em> <dfn class="decl" id="_ZN7Counter8setValueEi" title='Counter::setValue' data-ref="_ZN7Counter8setValueEi" >setValue</dfn>(<em>int</em> <dfn class="local col1 ref" id="1value" title='value' data-type='int' data-ref="1value" >value</dfn>);
<a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#74" title="public">signals</a>:
    <em>void</em> <dfn class="decl" id="_ZN7Counter12valueChangedEi" title='Counter::valueChanged' data-ref="_ZN7Counter12valueChangedEi" >valueChanged</dfn>(<em>int</em> <dfn class="local col2 ref" id="2newValue" title='newValue' data-type='int' data-ref="2newValue" >newValue</dfn>);
};
</pre>

<p>Somewhere in the <code>.cpp</code> file, we implement <code>setValue()</code></p>

<pre class="code"><em>void</em> <a class="type" href="counter.h.html#Counter" title='Counter' data-ref="Counter" >Counter</a>::<dfn class="decl" id="_ZN7Counter8setValueEi" title='Counter::setValue' data-ref="_ZN7Counter8setValueEi" >setValue</dfn>(<em>int</em> <dfn class="local col3 ref" id="3value" title='value' data-type='int' data-ref="3value" >value</dfn>)
{
    <b>if</b> (<span class="local col3 ref" title='value' data-ref="3value" >value</span> != <a class="member" href="counter.h.html#Counter::m_value" title='Counter::m_value' data-ref="Counter::m_value" >m_value</a>) {
        <a class="member" href="counter.h.html#Counter::m_value" title='Counter::m_value' data-ref="Counter::m_value" >m_value</a> = <span class="local col3 ref" title='value' data-ref="3value" >value</span>;
        <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#82" title="">emit</a> <a class="member" href="counter.h.html#_ZN7Counter12valueChangedEi" title='Counter::valueChanged' data-ref="_ZN7Counter12valueChangedEi" >valueChanged</a>(<span class="local col3 ref" title='value' data-ref="3value" >value</span>);
    }
}
</pre>

<p>Then one can use this Counter object like this:</p>

<pre class="code">  <a class="type" href="counter.h.html#Counter" title='Counter' data-ref="Counter" >Counter</a> <dfn class="local col4 ref" id="4a" title='a' data-type='Counter' data-ref="4a" >a</dfn>, <dfn class="local col5 ref" id="5b" title='b' data-type='Counter' data-ref="5b" >b</dfn>;
  <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a>::<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#_ZN7QObject7connectEPKS_PKcS1_S3_N2Qt14ConnectionTypeE" title='QObject::connect' data-ref="_ZN7QObject7connectEPKS_PKcS1_S3_N2Qt14ConnectionTypeE" data-proj="qtbase" >connect</a>(&amp;<span class="local col4 ref" title='a' data-ref="4a" >a</span>, <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#218" title="qFlagLocation(&quot;2&quot;&quot;valueChanged(int)&quot; &quot;\0&quot; &quot;/home/olivier/woboq/web/woboqwebsite/data/blogs/how-qt-signals-slots-work.data/counter.cpp&quot; &quot;:&quot; &quot;14&quot;)">SIGNAL</a>(valueChanged(<em>int</em>)),
                   &amp;<span class="local col5 ref" title='b' data-ref="5b" >b</span>, <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#217" title="qFlagLocation(&quot;1&quot;&quot;setValue(int)&quot; &quot;\0&quot; &quot;/home/olivier/woboq/web/woboqwebsite/data/blogs/how-qt-signals-slots-work.data/counter.cpp&quot; &quot;:&quot; &quot;15&quot;)">SLOT</a>(setValue(<em>int</em>)));

  <span class="local col4 ref" title='a' data-ref="4a" >a</span>.<a class="ref" href="counter.h.html#_ZN7Counter8setValueEi" title='Counter::setValue' data-ref="_ZN7Counter8setValueEi" >setValue</a>(<var>12</var>);  <i>// a.value() == 12, b.value() == 12</i>
</pre>


<p>This is the original syntax that has almost not changed since the beginning of Qt in 1992.</p>

<p>But even if the basic API has not changed since the beginning, its implementation has been changed several times.
New features have been added and a lot happened under the hood.
There is no magic involved and this blog post will show you how it works.</p>


<h2>MOC, the Meta Object Compiler</h2>

<p>The Qt signals/slots and property system are based on the ability to introspect the objects at runtime.
Introspection means being able to list the methods and properties of an object and have all
kinds of information about them
such as the type of their arguments.<br/>
QtScript and QML would have hardly been possible without that ability.</p>

<p>C++ does not offer introspection support natively, so Qt comes with a tool to provide it.
That tool is MOC.
It is a <em>code generator</em>  (and NOT a preprocessor like some people call it).</p>

<p>It parses the header files and generates an additional C++ file that is compiled with the rest of the program.
That generated C++ file contains all the information required for the introspection.</p>

<p>Qt has sometimes been criticized by language purists because of this extra code generator.
I will let the <a href="http://qt-project.org/doc/qt-4.8/templates.html">Qt documentation respond to this criticism</a>.
There is nothing wrong with code generators and the MOC is of a great help.
</p>

<h2>Magic Macros</h2>

<p>Can you spot the <em>keywords</em> that are not pure C++ keywords?
  <code>signals, slots, Q_OBJECT, emit, SIGNAL, SLOT</code>.
Those are known as the Qt extension to C++. They are in fact simple macros, defined in
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#66">qobjectdefs.h</a>
</p>


<pre class="brush: cpp">
#define signals public
#define slots /* nothing */
</pre>

<p>That is right, signals and slots are simple functions: the compiler will handle them them like any other functions.
The macros still serve a purpose though: the <code>MOC</code> will see them.</p>

<p>Signals were protected in Qt4 and before. They are becoming public in Qt5 in order to enable
	<a href="http://woboq.com/blog/new-signals-slots-syntax-in-qt5.html">the new syntax</a>.
</p>

<pre class="brush: cpp">
#define Q_OBJECT \
public: \
    static const QMetaObject staticMetaObject; \
    virtual const QMetaObject *metaObject() const; \
    virtual void *qt_metacast(const char *); \
    virtual int qt_metacall(QMetaObject::Call, int, void **); \
    QT_TR_FUNCTIONS /* translations helper */ \
private: \
    Q_DECL_HIDDEN static void qt_static_metacall(QObject *, QMetaObject::Call, int, void **);
</pre>

<p><code>Q_OBJECT</code> defines a bunch of functions and a static <code>QMetaObject</code>
Those functions are implemented in the file generated by MOC.</p>


<pre class="brush: cpp">
#define emit /* nothing */
</pre>

<p><code>emit</code> is an empty macro.  It is not even parsed by MOC. In other words, emit is just optional and means nothing (except
	being a hint to the developer).</p>


<pre class="brush: cpp">
Q_CORE_EXPORT const char *qFlagLocation(const char *method);
#ifndef QT_NO_DEBUG
# define QLOCATION &quot;\0&quot; __FILE__ &quot;:&quot; QTOSTRING(__LINE__)
# define SLOT(a)     qFlagLocation(&quot;1&quot;#a QLOCATION)
# define SIGNAL(a)   qFlagLocation(&quot;2&quot;#a QLOCATION)
#else
# define SLOT(a)     &quot;1&quot;#a
# define SIGNAL(a)   &quot;2&quot;#a
#endif
</pre>


<p>Those macros just use the preprocessor to convert the parameter into a string, and add a code in front.</p>

<p>In debug mode we also annotate the string with the file location for a warning message if the signal connection did not work.
This was added in Qt 4.5 in a compatible way.  In order to know which strings have the line information,
we use <code>qFlagLocation</code> which will register the string address in a table with two entries. </p>


<h2>MOC Generated Code</h2>

<p>We will now go over portion of the code generated by <code>moc</code> in Qt5.</p>

<h3>The QMetaObject</h3>

<pre class="code"><em>const</em> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a> <span class="type" title='Counter' data-ref="Counter" >Counter</span>::<dfn class="ref" id="_ZN7Counter16staticMetaObjectE" title='Counter::staticMetaObject' data-ref="_ZN7Counter16staticMetaObjectE" >staticMetaObject</dfn> = {
    { &amp;<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a>::<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#117" title='QObject::staticMetaObject' data-ref="_ZN7QObject16staticMetaObjectE" data-proj="qtbase" >staticMetaObject</a>, <span class="ref" title='qt_meta_stringdata_Counter' data-ref="_ZL26qt_meta_stringdata_Counter" >qt_meta_stringdata_Counter</span>.<span class="ref" title='qt_meta_stringdata_Counter_t::data' data-ref="qt_meta_stringdata_Counter_t::data" >data</span>,
      <span class="ref" title='qt_meta_data_Counter' data-ref="_ZL20qt_meta_data_Counter" >qt_meta_data_Counter</span>,  <span class="ref" title='Counter::qt_static_metacall' data-ref="_ZN7Counter18qt_static_metacallEP7QObjectN11QMetaObject4CallEiPPv" >qt_static_metacall</span>, <var>0</var>, <var>0</var>}
};


<em>const</em> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a> *<span class="type" title='Counter' data-ref="Counter" >Counter</span>::<dfn class="virtual decl" id="_ZNK7Counter10metaObjectEv" title='Counter::metaObject' data-ref="_ZNK7Counter10metaObjectEv" >metaObject</dfn>() <em>const</em>
{
    <b>return</b> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a>::<a class="member" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject::d_ptr" title='QObject::d_ptr' data-ref="QObject::d_ptr" data-proj="qtbase" >d_ptr</a><a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qscopedpointer.h.html#_ZNK14QScopedPointerptEv" title='QScopedPointer::operator-&gt;' data-ref="_ZNK14QScopedPointerptEv" data-proj="qtbase" >-&gt;</a><a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObjectData::metaObject" title='QObjectData::metaObject' data-ref="QObjectData::metaObject" data-proj="qtbase" >metaObject</a> ? <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a>::<a class="member" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject::d_ptr" title='QObject::d_ptr' data-ref="QObject::d_ptr" data-proj="qtbase" >d_ptr</a><a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qscopedpointer.h.html#_ZNK14QScopedPointerptEv" title='QScopedPointer::operator-&gt;' data-ref="_ZNK14QScopedPointerptEv" data-proj="qtbase" >-&gt;</a><a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#_ZNK11QObjectData17dynamicMetaObjectEv" title='QObjectData::dynamicMetaObject' data-ref="_ZNK11QObjectData17dynamicMetaObjectEv" data-proj="qtbase" >dynamicMetaObject</a>() : &amp;<span class="member" title='Counter::staticMetaObject' data-ref="_ZN7Counter16staticMetaObjectE" >staticMetaObject</span>;
}
</pre>

<p>We see here the implementation of <code>Counter::metaObject()</code> and <code>Counter::staticMetaObject</code>.
They are declared in the <code>Q_OBJECT</code> macro. <code>QObject::d_ptr->metaObject</code>
is only used for dynamic meta objects
(QML Objects), so in general, the virtual function <code>metaObject()</code> just returns the
<code>staticMetaObject</code> of the class.</p>

<p>The <code>staticMetaObject</code> is constructed in the read-only data. QMetaObject as defined in
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject">qobjectdefs.h</a>
looks like this:</p>

<pre class="code"><b>struct</b> <dfn class="type" id="QMetaObject" title='QMetaObject' data-ref="QMetaObject" >QMetaObject</dfn>
{
    <i>/* ... Skiped all the public functions ... */</i>

    <b>enum</b> <dfn class="type" id="QMetaObject::Call" title='QMetaObject::Call' data-ref="QMetaObject::Call" >Call</dfn> { <dfn class="enum" id="QMetaObject::Call::InvokeMetaMethod" title='QMetaObject::Call::InvokeMetaMethod' data-ref="QMetaObject::Call::InvokeMetaMethod" >InvokeMetaMethod</dfn>, <dfn class="enum" id="QMetaObject::Call::ReadProperty" title='QMetaObject::Call::ReadProperty' data-ref="QMetaObject::Call::ReadProperty" >ReadProperty</dfn>, <dfn class="enum" id="QMetaObject::Call::WriteProperty" title='QMetaObject::Call::WriteProperty' data-ref="QMetaObject::Call::WriteProperty" >WriteProperty</dfn>, <i>/*...*/</i> };

    <b>struct</b> { <i>// private data</i>
        <em>const</em> <span class="type" title='QMetaObject' data-ref="QMetaObject" >QMetaObject</span> *<dfn class="decl" id="QMetaObject::{anonymous}::superdata" title='QMetaObject::&lt;anonymous struct&gt;::superdata' data-ref="QMetaObject::{anonymous}::superdata" >superdata</dfn>;
        <em>const</em> <span class="typedef" title='QByteArrayData' data-ref="QByteArrayData" >QByteArrayData</span> *<dfn class="decl" id="QMetaObject::{anonymous}::stringdata" title='QMetaObject::&lt;anonymous struct&gt;::stringdata' data-ref="QMetaObject::{anonymous}::stringdata" >stringdata</dfn>;
        <em>const</em> <a class="typedef" href="http://code.woboq.org/qt5/include/sys/types.h.html#uint" title='uint' data-ref="uint" data-proj="include" >uint</a> *<dfn class="decl" id="QMetaObject::{anonymous}::data" title='QMetaObject::&lt;anonymous struct&gt;::data' data-ref="QMetaObject::{anonymous}::data" >data</dfn>;
        <b>typedef</b> <em>void</em> (*<dfn class="typedef" id="QMetaObject::{anonymousstruct}::StaticMetacallFunction" title='QMetaObject::&lt;anonymous struct&gt;::StaticMetacallFunction' data-ref="QMetaObject::{anonymousstruct}::StaticMetacallFunction" >StaticMetacallFunction</dfn>)(<span class="type" title='QObject' data-ref="QObject" >QObject</span> *, <span class="type" title='QMetaObject' data-ref="QMetaObject" >QMetaObject</span>::<span class="type" title='QMetaObject::Call' data-ref="QMetaObject::Call" >Call</span>, <em>int</em>, <em>void</em> **);
        <span class="typedef" title='QMetaObject::&lt;anonymous struct&gt;::StaticMetacallFunction' data-ref="QMetaObject::{anonymousstruct}::StaticMetacallFunction" >StaticMetacallFunction</span> <dfn class="decl" id="QMetaObject::{anonymous}::static_metacall" title='QMetaObject::&lt;anonymous struct&gt;::static_metacall' data-ref="QMetaObject::{anonymous}::static_metacall" >static_metacall</dfn>;
        <em>const</em> <span class="type" title='QMetaObject' data-ref="QMetaObject" >QMetaObject</span> **<dfn class="decl" id="QMetaObject::{anonymous}::relatedMetaObjects" title='QMetaObject::&lt;anonymous struct&gt;::relatedMetaObjects' data-ref="QMetaObject::{anonymous}::relatedMetaObjects" >relatedMetaObjects</dfn>;
        <em>void</em> *<dfn class="decl" id="QMetaObject::{anonymous}::extradata" title='QMetaObject::&lt;anonymous struct&gt;::extradata' data-ref="QMetaObject::{anonymous}::extradata" >extradata</dfn>; <i>//reserved for future use</i>
    } <dfn class="decl" id="QMetaObject::d" title='QMetaObject::d' data-ref="QMetaObject::d" >d</dfn>;
};
</pre>

<p>The <code>d</code> indirection is there to symbolize that all the member should be private. They are not private
in order to keep it a POD and allow static initialization.</p>

<p>The <code>QMetaObject</code> is initialized with the meta object of the parent object
(<code>QObject::staticMetaObject</code> in this case) as <code>superdata</code>. <code>stringdata</code> and
<code>data</code> are initialized with some data explained later in this article.
<code>static_metacall</code> is a function pointer initialized to
<code>Counter::qt_static_metacall</code>.</p>

<h3>Introspection Tables</h3>

<p>First, let us analyze the integer data of QMetaObject.</p>

<pre class="code"><em>static</em> <em>const</em> <a class="typedef" href="http://code.woboq.org/qt5/include/sys/types.h.html#uint" title='uint' data-ref="uint" data-proj="include" >uint</a> <dfn class="ref" id="_ZL20qt_meta_data_Counter" title='qt_meta_data_Counter' data-ref="_ZL20qt_meta_data_Counter" >qt_meta_data_Counter</dfn>[] = {

 <i>// content:</i>
       <var>7</var>,       <i>// revision</i>
       <var>0</var>,       <i>// classname</i>
       <var>0</var>,    <var>0</var>, <i>// classinfo</i>
       <var>2</var>,   <var>14</var>, <i>// methods</i>
       <var>0</var>,    <var>0</var>, <i>// properties</i>
       <var>0</var>,    <var>0</var>, <i>// enums/sets</i>
       <var>0</var>,    <var>0</var>, <i>// constructors</i>
       <var>0</var>,       <i>// flags</i>
       <var>1</var>,       <i>// signalCount</i>

 <i>// signals: name, argc, parameters, tag, flags</i>
       <var>1</var>,    <var>1</var>,   <var>24</var>,    <var>2</var>, <var>0x05</var>,

 <i>// slots: name, argc, parameters, tag, flags</i>
       <var>4</var>,    <var>1</var>,   <var>27</var>,    <var>2</var>, <var>0x0a</var>,

 <i>// signals: parameters</i>
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetatype.h.html#QMetaType" title='QMetaType' data-ref="QMetaType" data-proj="qtbase" >QMetaType</a>::<a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetatype.h.html#205" title='QMetaType::Type::Void' data-ref="QMetaType::Type::Void" data-proj="qtbase" >Void</a>, <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetatype.h.html#QMetaType" title='QMetaType' data-ref="QMetaType" data-proj="qtbase" >QMetaType</a>::<a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetatype.h.html#205" title='QMetaType::Type::Int' data-ref="QMetaType::Type::Int" data-proj="qtbase" >Int</a>,    <var>3</var>,

 <i>// slots: parameters</i>
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetatype.h.html#QMetaType" title='QMetaType' data-ref="QMetaType" data-proj="qtbase" >QMetaType</a>::<a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetatype.h.html#205" title='QMetaType::Type::Void' data-ref="QMetaType::Type::Void" data-proj="qtbase" >Void</a>, <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetatype.h.html#QMetaType" title='QMetaType' data-ref="QMetaType" data-proj="qtbase" >QMetaType</a>::<a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetatype.h.html#205" title='QMetaType::Type::Int' data-ref="QMetaType::Type::Int" data-proj="qtbase" >Int</a>,    <var>5</var>,

       <var>0</var>        <i>// eod</i>
};
</pre>

<p>The first 13 <code>int</code> consists of the header. When there are two columns,
the first column is the count
and the second column is the index in this array where the description starts.<br/>
In this case we have 2 methods, and the methods description starts at index 14.</p>
<p>The method descriptions are composed of 5 <code>int</code>.
The first one is the name, it is an index in the string table
(we will look into the details later).  The second integer is the number of parameters,
 followed by the index at which one can find the parameter description.
 We will ignore the tag and flags for now.
For each function, <code>moc</code> also saves the return type of each parameter,
 their type and index to the name.
</p>

<h3>String Table</h3>

<pre class="code"><b>struct</b> <dfn class="type" id="qt_meta_stringdata_Counter_t" title='qt_meta_stringdata_Counter_t' data-ref="qt_meta_stringdata_Counter_t" >qt_meta_stringdata_Counter_t</dfn> {
    <a class="typedef" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QByteArrayData" title='QByteArrayData' data-ref="QByteArrayData" data-proj="qtbase" >QByteArrayData</a> <dfn class="decl" id="qt_meta_stringdata_Counter_t::data" title='qt_meta_stringdata_Counter_t::data' data-ref="qt_meta_stringdata_Counter_t::data" >data</dfn>[<var>6</var>];
    <em>char</em> <dfn class="decl" id="qt_meta_stringdata_Counter_t::stringdata" title='qt_meta_stringdata_Counter_t::stringdata' data-ref="qt_meta_stringdata_Counter_t::stringdata" >stringdata</dfn>[<var>47</var>];
};
<u>#define QT_MOC_LITERAL(idx, ofs, len) \</u>
<u>    Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \</u>
<u>    offsetof(<span class="type" title='qt_meta_stringdata_Counter_t' data-ref="qt_meta_stringdata_Counter_t" >qt_meta_stringdata_Counter_t</span>, stringdata) + ofs \</u>
<u>        - idx * sizeof(<a class="typedef" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QByteArrayData" title='QByteArrayData' data-ref="QByteArrayData" data-proj="qtbase" >QByteArrayData</a>) \</u>
<u>    )</u>
<em>static</em> <em>const</em> <span class="type" title='qt_meta_stringdata_Counter_t' data-ref="qt_meta_stringdata_Counter_t" >qt_meta_stringdata_Counter_t</span> <dfn class="ref" id="_ZL26qt_meta_stringdata_Counter" title='qt_meta_stringdata_Counter' data-ref="_ZL26qt_meta_stringdata_Counter" >qt_meta_stringdata_Counter</dfn> = {
    {
<span class="macro" title="{ { { (-1) } }, 7, 0, 0, __builtin_offsetof(qt_meta_stringdata_Counter_t, stringdata) + 0 - 0 * sizeof(QByteArrayData) }">QT_MOC_LITERAL</span>(<var>0</var>, <var>0</var>, <var>7</var>),
<span class="macro" title="{ { { (-1) } }, 12, 0, 0, __builtin_offsetof(qt_meta_stringdata_Counter_t, stringdata) + 8 - 1 * sizeof(QByteArrayData) }">QT_MOC_LITERAL</span>(<var>1</var>, <var>8</var>, <var>12</var>),
<span class="macro" title="{ { { (-1) } }, 0, 0, 0, __builtin_offsetof(qt_meta_stringdata_Counter_t, stringdata) + 21 - 2 * sizeof(QByteArrayData) }">QT_MOC_LITERAL</span>(<var>2</var>, <var>21</var>, <var>0</var>),
<span class="macro" title="{ { { (-1) } }, 8, 0, 0, __builtin_offsetof(qt_meta_stringdata_Counter_t, stringdata) + 22 - 3 * sizeof(QByteArrayData) }">QT_MOC_LITERAL</span>(<var>3</var>, <var>22</var>, <var>8</var>),
<span class="macro" title="{ { { (-1) } }, 8, 0, 0, __builtin_offsetof(qt_meta_stringdata_Counter_t, stringdata) + 31 - 4 * sizeof(QByteArrayData) }">QT_MOC_LITERAL</span>(<var>4</var>, <var>31</var>, <var>8</var>),
<span class="macro" title="{ { { (-1) } }, 5, 0, 0, __builtin_offsetof(qt_meta_stringdata_Counter_t, stringdata) + 40 - 5 * sizeof(QByteArrayData) }">QT_MOC_LITERAL</span>(<var>5</var>, <var>40</var>, <var>5</var>)
    },
    <q>"Counter\0valueChanged\0\0newValue\0setValue\0"</q>
    <q>"value\0"</q>
};
<u>#undef QT_MOC_LITERAL</u>
</pre>

<p>This is basically a static array of <code>QByteArray</code>.
the <code>QT_MOC_LITERAL</code> macro creates a
static <code>QByteArray</code> that references a particular index in the string below.</p>

<h3>Signals</h3>

<p>The MOC also implements the signals. They are simple functions that just create an array of pointers to the
arguments and pass that to <code>QMetaObject::activate</code>.  The first element of the array is
the return value. In our example it is 0 because the return value is <code>void</code>.<br/>
The 3rd parameter passed to activate is the signal index (0 in that case).</p>

<pre class="code"><i>// SIGNAL 0</i>
<em>void</em> <span class="type" title='Counter' data-ref="Counter" >Counter</span>::<dfn class="decl" id="_ZN7Counter12valueChangedEi" title='Counter::valueChanged' data-ref="_ZN7Counter12valueChangedEi" >valueChanged</dfn>(<em>int</em> <dfn class="local col0 ref" id="20_t1" title='_t1' data-type='int' data-ref="20_t1" >_t1</dfn>)
{
    <em>void</em> *<dfn class="local col1 ref" id="21_a" title='_a' data-type='void *[2]' data-ref="21_a" >_a</dfn>[] = { <var>0</var>, <b>const_cast</b>&lt;<em>void</em>*&gt;(<b>reinterpret_cast</b>&lt;<em>const</em> <em>void</em>*&gt;(&amp;<span class="local col0 ref" title='_t1' data-ref="20_t1" >_t1</span>)) };
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#_ZN11QMetaObject8activateEP7QObjectPKS_iPPv" title='QMetaObject::activate' data-ref="_ZN11QMetaObject8activateEP7QObjectPKS_iPPv" data-proj="qtbase" >activate</a>(<b>this</b>, &amp;<span class="member" title='Counter::staticMetaObject' data-ref="_ZN7Counter16staticMetaObjectE" >staticMetaObject</span>, <var>0</var>, <span class="local col1 ref" title='_a' data-ref="21_a" >_a</span>);
}
</pre>

<h3>Calling a Slot</h3>

<p>It is also possible to call a slot by its index in the <code>qt_static_metacall</code> function:</p>

<pre class="code">
<em>void</em> <span class="type" title='Counter' data-ref="Counter" >Counter</span>::<dfn class="decl" id="_ZN7Counter18qt_static_metacallEP7QObjectN11QMetaObject4CallEiPPv" title='Counter::qt_static_metacall' data-ref="_ZN7Counter18qt_static_metacallEP7QObjectN11QMetaObject4CallEiPPv" >qt_static_metacall</dfn>(<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a> *<dfn class="local col8 ref" id="8_o" title='_o' data-type='QObject *' data-ref="8_o" >_o</dfn>, <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject::Call" title='QMetaObject::Call' data-ref="QMetaObject::Call" data-proj="qtbase" >Call</a> <dfn class="local col9 ref" id="9_c" title='_c' data-type='QMetaObject::Call' data-ref="9_c" >_c</dfn>, <em>int</em> <dfn class="local col0 ref" id="10_id" title='_id' data-type='int' data-ref="10_id" >_id</dfn>, <em>void</em> **<dfn class="local col1 ref" id="11_a" title='_a' data-type='void **' data-ref="11_a" >_a</dfn>)
{
    <b>if</b> (<span class="local col9 ref" title='_c' data-ref="9_c" >_c</span> == <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject::Call::InvokeMetaMethod" title='QMetaObject::Call::InvokeMetaMethod' data-ref="QMetaObject::Call::InvokeMetaMethod" data-proj="qtbase" >InvokeMetaMethod</a>) {
        <span class="type" title='Counter' data-ref="Counter" >Counter</span> *<dfn class="local col2 ref" id="12_t" title='_t' data-type='Counter *' data-ref="12_t" >_t</dfn> = <b>static_cast</b>&lt;<span class="type" title='Counter' data-ref="Counter" >Counter</span> *&gt;(<span class="local col8 ref" title='_o' data-ref="8_o" >_o</span>);
        <b>switch</b> (<span class="local col0 ref" title='_id' data-ref="10_id" >_id</span>) {
        <b>case</b> <var>0</var>: <span class="local col2 ref" title='_t' data-ref="12_t" >_t</span>-&gt;<span class="member" title='Counter::valueChanged' data-ref="_ZN7Counter12valueChangedEi" >valueChanged</span>((*<b>reinterpret_cast</b>&lt; <em>int</em>(*)&gt;(<span class="local col1 ref" title='_a' data-ref="11_a" >_a</span>[<var>1</var>]))); <b>break</b>;
        <b>case</b> <var>1</var>: <span class="local col2 ref" title='_t' data-ref="12_t" >_t</span>-&gt;<span class="member" title='Counter::setValue' data-ref="_ZN7Counter8setValueEi" >setValue</span>((*<b>reinterpret_cast</b>&lt; <em>int</em>(*)&gt;(<span class="local col1 ref" title='_a' data-ref="11_a" >_a</span>[<var>1</var>]))); <b>break</b>;
        <b>default</b>: ;
        }
</pre>

<p>The array pointers to the argument is the same format as the one used for the signal.
<code>_a[0]</code> is not touched because everything here returns void.</p>

<h2>A Note About Indexes.</h2>

<p>
In each QMetaObject, the slots, signals and other invokable methods of that object
are given an index, starting from 0. They are ordered so that the signals come first,
 then the slots and then the other methods.
This index is called internally the <b>relative index</b>. They do not include the indexes of the parents.</p>

<p>But in general, we do not want to know a more global index that is not relative to a particular class,
   but include all the other methods in the inheritance chain.
   To that, we just add an offset to that relative index and get the
   <b>absolute index</b>. It is the index used in the public API,
 returned by functions like <code>QMetaObject::indexOf{Signal,Slot,Method}</code></p>


<p>The connection mechanism uses a vector indexed by signals.
But all the slots waste space in the vector
and there are usually more slots than signals in an object.
So from Qt 4.6, a new internal <b>signal index</b> which only includes the signal index is used.</p>

<p>While developing with Qt, you only need to know about the absolute method index.
But while browsing the Qt's QObject source code, you must be aware
of the difference between those three.</p>

<h2>How Connecting Works.</h2>
<p>The first thing Qt does when doing a connection is to find out the index of the signal and the slot.
  Qt will look up in the string tables of the meta object to find the corresponding indexes.</p>


<p>Then a <code>QObjectPrivate::Connection</code> object is created and added in the internal linked lists.</p>

<p>What information needs to be stored for each connection?
We need a way to quickly access the connections for a given signal index.
Since there can be several slots connected to the same signal, we need for each
signal to have a list of the connected slots. Each connection must contain the
receiver object, and the index of the slot.
We also want the connections to be automatically destroyed when the receiver is destroyed,
so each receiver object needs to know who is connected to him so he can clear the connection.</p>

<p>Here is the <code>QObjectPrivate::Connection</code> as defined in
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection">qobject_p.h</a> :</p>

<pre class="code"><b>struct</b> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate" title='QObjectPrivate' data-ref="QObjectPrivate" data-proj="qtbase" >QObjectPrivate</a>::<dfn class="type" id="QObjectPrivate::Connection" title='QObjectPrivate::Connection' data-ref="QObjectPrivate::Connection" >Connection</dfn>
{
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a> *<dfn class="decl" id="QObjectPrivate::Connection::sender" title='QObjectPrivate::Connection::sender' data-ref="QObjectPrivate::Connection::sender" >sender</dfn>;
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a> *<dfn class="decl" id="QObjectPrivate::Connection::receiver" title='QObjectPrivate::Connection::receiver' data-ref="QObjectPrivate::Connection::receiver" >receiver</dfn>;
    <b>union</b> {
        <a class="typedef" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::StaticMetaCallFunction" title='QObjectPrivate::StaticMetaCallFunction' data-ref="QObjectPrivate::StaticMetaCallFunction" data-proj="qtbase" >StaticMetaCallFunction</a> <dfn class="decl" id="QObjectPrivate::Connection::{anonymous}::callFunction" title='QObjectPrivate::Connection::&lt;anonymous union&gt;::callFunction' data-ref="QObjectPrivate::Connection::{anonymous}::callFunction" >callFunction</dfn>;
        <span class="namespace">QtPrivate::</span><a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_impl.h.html#QtPrivate::QSlotObjectBase" title='QtPrivate::QSlotObjectBase' data-ref="QtPrivate::QSlotObjectBase" data-proj="qtbase" >QSlotObjectBase</a> *<dfn class="decl" id="QObjectPrivate::Connection::{anonymous}::slotObj" title='QObjectPrivate::Connection::&lt;anonymous union&gt;::slotObj' data-ref="QObjectPrivate::Connection::{anonymous}::slotObj" >slotObj</dfn>;
    };
    <i>// The next pointer for the singly-linked ConnectionList</i>
    <span class="type" title='QObjectPrivate::Connection' data-ref="QObjectPrivate::Connection" >Connection</span> *<dfn class="decl" id="QObjectPrivate::Connection::nextConnectionList" title='QObjectPrivate::Connection::nextConnectionList' data-ref="QObjectPrivate::Connection::nextConnectionList" >nextConnectionList</dfn>;
    <i>//senders linked list</i>
    <span class="type" title='QObjectPrivate::Connection' data-ref="QObjectPrivate::Connection" >Connection</span> *<dfn class="decl" id="QObjectPrivate::Connection::next" title='QObjectPrivate::Connection::next' data-ref="QObjectPrivate::Connection::next" >next</dfn>;
    <span class="type" title='QObjectPrivate::Connection' data-ref="QObjectPrivate::Connection" >Connection</span> **<dfn class="decl" id="QObjectPrivate::Connection::prev" title='QObjectPrivate::Connection::prev' data-ref="QObjectPrivate::Connection::prev" >prev</dfn>;
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qatomic.h.html#QAtomicPointer" title='QAtomicPointer' data-ref="QAtomicPointer" data-proj="qtbase" >QAtomicPointer</a>&lt;<em>const</em> <em>int</em>&gt; <dfn class="decl" id="QObjectPrivate::Connection::argumentTypes" title='QObjectPrivate::Connection::argumentTypes' data-ref="QObjectPrivate::Connection::argumentTypes" >argumentTypes</dfn>;
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qatomic.h.html#QAtomicInt" title='QAtomicInt' data-ref="QAtomicInt" data-proj="qtbase" >QAtomicInt</a> <dfn class="decl" id="QObjectPrivate::Connection::ref_" title='QObjectPrivate::Connection::ref_' data-ref="QObjectPrivate::Connection::ref_" >ref_</dfn>;
    <a class="typedef" href="http://code.woboq.org/qt5/include/sys/types.h.html#ushort" title='ushort' data-ref="ushort" data-proj="include" >ushort</a> <dfn class="decl" id="QObjectPrivate::Connection::method_offset" title='QObjectPrivate::Connection::method_offset' data-ref="QObjectPrivate::Connection::method_offset" >method_offset</dfn>;
    <a class="typedef" href="http://code.woboq.org/qt5/include/sys/types.h.html#ushort" title='ushort' data-ref="ushort" data-proj="include" >ushort</a> <dfn class="decl" id="QObjectPrivate::Connection::method_relative" title='QObjectPrivate::Connection::method_relative' data-ref="QObjectPrivate::Connection::method_relative" >method_relative</dfn>;
    <a class="typedef" href="http://code.woboq.org/qt5/include/sys/types.h.html#uint" title='uint' data-ref="uint" data-proj="include" >uint</a> <dfn class="decl" id="QObjectPrivate::Connection::signal_index" title='QObjectPrivate::Connection::signal_index' data-ref="QObjectPrivate::Connection::signal_index" >signal_index</dfn> : <var>27</var>; <i>// In signal range (see QObjectPrivate::signalIndex())</i>
    <a class="typedef" href="http://code.woboq.org/qt5/include/sys/types.h.html#ushort" title='ushort' data-ref="ushort" data-proj="include" >ushort</a> <dfn class="decl" id="QObjectPrivate::Connection::connectionType" title='QObjectPrivate::Connection::connectionType' data-ref="QObjectPrivate::Connection::connectionType" >connectionType</dfn> : <var>3</var>; <i>// 0 == auto, 1 == direct, 2 == queued, 4 == blocking</i>
    <a class="typedef" href="http://code.woboq.org/qt5/include/sys/types.h.html#ushort" title='ushort' data-ref="ushort" data-proj="include" >ushort</a> <dfn class="decl" id="QObjectPrivate::Connection::isSlotObject" title='QObjectPrivate::Connection::isSlotObject' data-ref="QObjectPrivate::Connection::isSlotObject" >isSlotObject</dfn> : <var>1</var>;
    <a class="typedef" href="http://code.woboq.org/qt5/include/sys/types.h.html#ushort" title='ushort' data-ref="ushort" data-proj="include" >ushort</a> <dfn class="decl" id="QObjectPrivate::Connection::ownArgumentTypes" title='QObjectPrivate::Connection::ownArgumentTypes' data-ref="QObjectPrivate::Connection::ownArgumentTypes" >ownArgumentTypes</dfn> : <var>1</var>;
    <dfn class="decl" id="_ZN14QObjectPrivate10ConnectionC1Ev" title='QObjectPrivate::Connection::Connection' data-ref="_ZN14QObjectPrivate10ConnectionC1Ev" >Connection</dfn>() : <span class="member" title='QObjectPrivate::Connection::nextConnectionList' data-ref="QObjectPrivate::Connection::nextConnectionList" >nextConnectionList</span>(<var>0</var>), <span class="member" title='QObjectPrivate::Connection::ref_' data-ref="QObjectPrivate::Connection::ref_" >ref_</span>(<var>2</var>), <span class="member" title='QObjectPrivate::Connection::ownArgumentTypes' data-ref="QObjectPrivate::Connection::ownArgumentTypes" >ownArgumentTypes</span>(<b>true</b>) {
        <i>//ref_ is 2 for the use in the internal lists, and for the use in QMetaObject::Connection</i>
    }
    <dfn class="decl" id="_ZN14QObjectPrivate10ConnectionD1Ev" title='QObjectPrivate::Connection::~Connection' data-ref="_ZN14QObjectPrivate10ConnectionD1Ev" >~</dfn>Connection();
    <em>int</em> <dfn class="decl" id="_ZNK14QObjectPrivate10Connection6methodEv" title='QObjectPrivate::Connection::method' data-ref="_ZNK14QObjectPrivate10Connection6methodEv" >method</dfn>() <em>const</em> { <b>return</b> <span class="member" title='QObjectPrivate::Connection::method_offset' data-ref="QObjectPrivate::Connection::method_offset" >method_offset</span> + <span class="member" title='QObjectPrivate::Connection::method_relative' data-ref="QObjectPrivate::Connection::method_relative" >method_relative</span>; }
    <em>void</em> <dfn class="decl" id="_ZN14QObjectPrivate10Connection3refEv" title='QObjectPrivate::Connection::ref' data-ref="_ZN14QObjectPrivate10Connection3refEv" >ref</dfn>() { <span class="member" title='QObjectPrivate::Connection::ref_' data-ref="QObjectPrivate::Connection::ref_" >ref_</span>.<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qbasicatomic.h.html#_ZN19QBasicAtomicInteger3refEv" title='QBasicAtomicInteger::ref' data-ref="_ZN19QBasicAtomicInteger3refEv" data-proj="qtbase" >ref</a>(); }
    <em>void</em> <dfn class="decl" id="_ZN14QObjectPrivate10Connection5derefEv" title='QObjectPrivate::Connection::deref' data-ref="_ZN14QObjectPrivate10Connection5derefEv" >deref</dfn>() {
        <b>if</b> (!<span class="member" title='QObjectPrivate::Connection::ref_' data-ref="QObjectPrivate::Connection::ref_" >ref_</span>.<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qbasicatomic.h.html#_ZN19QBasicAtomicInteger5derefEv" title='QBasicAtomicInteger::deref' data-ref="_ZN19QBasicAtomicInteger5derefEv" data-proj="qtbase" >deref</a>()) {
            <a class="macro" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qglobal.h.html#619" title="((!(!receiver)) ? qt_assert(&quot;!receiver&quot;,&quot;/home/olivier/woboq/web/woboqwebsite/data/blogs/how-qt-signals-slots-work.data/qobject_p.cpp&quot;,38) : qt_noop())">Q_ASSERT</a>(!<span class="member" title='QObjectPrivate::Connection::receiver' data-ref="QObjectPrivate::Connection::receiver" >receiver</span>);
            <b>delete</b> <b>this</b>;
        }
    }
};
</pre>

<p>Each object has then a connection vector: It is a vector which associates for each of the signals
a linked lists of <code>QObjectPrivate::Connection</code>.<br/>
Each object also has a reversed lists of connections the object is connected to for automatic deletion.
It is a doubly linked list.
</p>
<p><img src="http://woboq.com/blog/how-qt-signals-slots-work/qobject_connection.png" /></p>

<p>Linked lists are used because they allow to quickly add and remove objects.
They are implemented by having the pointers to the next/previous nodes within <code>QObjectPrivate::Connection</code><br/>
Note that the <code>prev</code> pointer of the <code>senderList</code> is a pointer to a pointer.
That is because we don't really point to the previous node, but rather to the pointer to the next in the previous node.
This pointer is only used when the connection is destroyed, and not to iterate backwards. It allows not to have a
special case for the first item.</p>

<p><img src="http://woboq.com/blog/how-qt-signals-slots-work/qobject_connection_node.png" /></p>


<h2>Signal Emission</h2>

<p>When we call a signal, we have seen that it calls the MOC
generated code which calls <code>QMetaObject::activate</code>.
</p>

<p>Here is an annotated version of its implementation from
<a href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.cpp.html#_ZN11QMetaObject8activateEP7QObjectPKS_iPPv">qobject.cpp</a>
</p>

<pre class="code"><em>void</em> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<dfn class="decl" id="_ZN11QMetaObject8activateEP7QObjectPKS_iPPv" title='QMetaObject::activate' data-ref="_ZN11QMetaObject8activateEP7QObjectPKS_iPPv" >activate</dfn>(<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a> *<dfn class="local col1 ref" id="1sender" title='sender' data-type='QObject *' data-ref="1sender" >sender</dfn>, <em>const</em> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a> *<dfn class="local col2 ref" id="2m" title='m' data-type='const QMetaObject *' data-ref="2m" >m</dfn>, <em>int</em> <dfn class="local col3 ref" id="3local_signal_index" title='local_signal_index' data-type='int' data-ref="3local_signal_index" >local_signal_index</dfn>,
                           <em>void</em> **<dfn class="local col4 ref" id="4argv" title='argv' data-type='void **' data-ref="4argv" >argv</dfn>)
{
    <a class="member" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#_ZN11QMetaObject8activateEP7QObjectiiPPv" title='QMetaObject::activate' data-ref="_ZN11QMetaObject8activateEP7QObjectiiPPv" data-proj="qtbase" >activate</a>(<span class="local col1 ref" title='sender' data-ref="1sender" >sender</span>, <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetaobject_p.h.html#QMetaObjectPrivate" title='QMetaObjectPrivate' data-ref="QMetaObjectPrivate" data-proj="qtbase" >QMetaObjectPrivate</a>::<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmetaobject_p.h.html#_ZN18QMetaObjectPrivate12signalOffsetEPK11QMetaObject" title='QMetaObjectPrivate::signalOffset' data-ref="_ZN18QMetaObjectPrivate12signalOffsetEPK11QMetaObject" data-proj="qtbase" >signalOffset</a>(<span class="local col2 ref" title='m' data-ref="2m" >m</span>), <span class="local col3 ref" title='local_signal_index' data-ref="3local_signal_index" >local_signal_index</span>, <span class="local col4 ref" title='argv' data-ref="4argv" >argv</span>);
    <i>/* We just forward to the next function here. We pass the signal offset of</i>
<i>     * the meta object rather than the QMetaObject itself</i>
<i>     * It is split into two functions because QML internals will call the later. */</i>
}

<em>void</em> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<dfn class="decl" id="_ZN11QMetaObject8activateEP7QObjectiiPPv" title='QMetaObject::activate' data-ref="_ZN11QMetaObject8activateEP7QObjectiiPPv" >activate</dfn>(<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a> *<dfn class="local col5 ref" id="5sender" title='sender' data-type='QObject *' data-ref="5sender" >sender</dfn>, <em>int</em> <dfn class="local col6 ref" id="6signalOffset" title='signalOffset' data-type='int' data-ref="6signalOffset" >signalOffset</dfn>, <em>int</em> <dfn class="local col7 ref" id="7local_signal_index" title='local_signal_index' data-type='int' data-ref="7local_signal_index" >local_signal_index</dfn>, <em>void</em> **<dfn class="local col8 ref" id="8argv" title='argv' data-type='void **' data-ref="8argv" >argv</dfn>)
{
    <em>int</em> <dfn class="local col9 ref" id="9signal_index" title='signal_index' data-type='int' data-ref="9signal_index" >signal_index</dfn> = <span class="local col6 ref" title='signalOffset' data-ref="6signalOffset" >signalOffset</span> + <span class="local col7 ref" title='local_signal_index' data-ref="7local_signal_index" >local_signal_index</span>;

    <i>/* The first thing we do is quickly check a bit-mask of 64 bits. If it is 0,</i>
<i>     * we are sure there is nothing connected to this signal, and we can return</i>
<i>     * quickly, which means emitting a signal connected to no slot is extremely</i>
<i>     * fast. */</i>
    <b>if</b> (!<span class="local col5 ref" title='sender' data-ref="5sender" >sender</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#119" title='QObject::d_func' data-ref="_ZN7QObject6d_funcEv" data-proj="qtbase" >d_func</a>()-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#_ZNK14QObjectPrivate17isSignalConnectedEj" title='QObjectPrivate::isSignalConnected' data-ref="_ZNK14QObjectPrivate17isSignalConnectedEj" data-proj="qtbase" >isSignalConnected</a>(<span class="local col9 ref" title='signal_index' data-ref="9signal_index" >signal_index</span>))
        <b>return</b>; <i>// nothing connected to these signals, and no spy</i>

    <i>/* ... Skipped some debugging and QML hooks, and some sanity check ... */</i>

    <i>/* We lock a mutex because all operations in the connectionLists are thread safe */</i>
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qmutex.h.html#QMutexLocker" title='QMutexLocker' data-ref="QMutexLocker" data-proj="qtbase" >QMutexLocker</a> <dfn class="local col0 ref" id="10locker" title='locker' data-type='QMutexLocker' data-ref="10locker" >locker</dfn>(<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.cpp.html#_ZL14signalSlotLockPK7QObject" title='signalSlotLock' data-ref="_ZL14signalSlotLockPK7QObject" data-proj="qtbase" >signalSlotLock</a>(<span class="local col5 ref" title='sender' data-ref="5sender" >sender</span>));

    <i>/* Get the ConnectionList for this signal.  I simplified a bit here. The real code</i>
<i>     * also refcount the list and do sanity checks */</i>
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.cpp.html#QObjectConnectionListVector" title='QObjectConnectionListVector' data-ref="QObjectConnectionListVector" data-proj="qtbase" >QObjectConnectionListVector</a> *<dfn class="local col1 ref" id="11connectionLists" title='connectionLists' data-type='QObjectConnectionListVector *' data-ref="11connectionLists" >connectionLists</dfn> = <span class="local col5 ref" title='sender' data-ref="5sender" >sender</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#119" title='QObject::d_func' data-ref="_ZN7QObject6d_funcEv" data-proj="qtbase" >d_func</a>()-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::connectionLists" title='QObjectPrivate::connectionLists' data-ref="QObjectPrivate::connectionLists" data-proj="qtbase" >connectionLists</a>;
    <em>const</em> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate" title='QObjectPrivate' data-ref="QObjectPrivate" data-proj="qtbase" >QObjectPrivate</a>::<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::ConnectionList" title='QObjectPrivate::ConnectionList' data-ref="QObjectPrivate::ConnectionList" data-proj="qtbase" >ConnectionList</a> *<dfn class="local col2 ref" id="12list" title='list' data-type='const QObjectPrivate::ConnectionList *' data-ref="12list" >list</dfn> =
        &amp;<span class="local col1 ref" title='connectionLists' data-ref="11connectionLists" >connectionLists</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qvector.h.html#_ZNK7QVector2atEi" title='QVector::at' data-ref="_ZNK7QVector2atEi" data-proj="qtbase" >at</a>(<span class="local col9 ref" title='signal_index' data-ref="9signal_index" >signal_index</span>);

    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate" title='QObjectPrivate' data-ref="QObjectPrivate" data-proj="qtbase" >QObjectPrivate</a>::<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection" title='QObjectPrivate::Connection' data-ref="QObjectPrivate::Connection" data-proj="qtbase" >Connection</a> *<dfn class="local col3 ref" id="13c" title='c' data-type='QObjectPrivate::Connection *' data-ref="13c" >c</dfn> = <span class="local col2 ref" title='list' data-ref="12list" >list</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::ConnectionList::first" title='QObjectPrivate::ConnectionList::first' data-ref="QObjectPrivate::ConnectionList::first" data-proj="qtbase" >first</a>;
    <b>if</b> (!c) <b>continue</b>;
    <i>// We need to check against last here to ensure that signals added</i>
<i>    // during the signal emission are not emitted in this emission.</i>
    <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate" title='QObjectPrivate' data-ref="QObjectPrivate" data-proj="qtbase" >QObjectPrivate</a>::<a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection" title='QObjectPrivate::Connection' data-ref="QObjectPrivate::Connection" data-proj="qtbase" >Connection</a> *<dfn class="local col4 ref" id="14last" title='last' data-type='QObjectPrivate::Connection *' data-ref="14last" >last</dfn> = <span class="local col2 ref" title='list' data-ref="12list" >list</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::ConnectionList::last" title='QObjectPrivate::ConnectionList::last' data-ref="QObjectPrivate::ConnectionList::last" data-proj="qtbase" >last</a>;

    <i>/* Now iterates, for each slot */</i>
    <b>do</b> {
        <b>if</b> (!<span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::receiver" title='QObjectPrivate::Connection::receiver' data-ref="QObjectPrivate::Connection::receiver" data-proj="qtbase" >receiver</a>)
            <b>continue</b>;

        <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#QObject" title='QObject' data-ref="QObject" data-proj="qtbase" >QObject</a> * <em>const</em> <dfn class="local col5 ref" id="15receiver" title='receiver' data-type='QObject *const' data-ref="15receiver" >receiver</dfn> = <span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::receiver" title='QObjectPrivate::Connection::receiver' data-ref="QObjectPrivate::Connection::receiver" data-proj="qtbase" >receiver</a>;
        <em>const</em> <em>bool</em> <dfn class="local col6 ref" id="16receiverInSameThread" title='receiverInSameThread' data-type='const bool' data-ref="16receiverInSameThread" >receiverInSameThread</dfn> = <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qthread.h.html#QThread" title='QThread' data-ref="QThread" data-proj="qtbase" >QThread</a>::<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qthread.h.html#_ZN7QThread15currentThreadIdEv" title='QThread::currentThreadId' data-ref="_ZN7QThread15currentThreadIdEv" data-proj="qtbase" >currentThreadId</a>() == <span class="local col5 ref" title='receiver' data-ref="15receiver" >receiver</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#119" title='QObject::d_func' data-ref="_ZN7QObject6d_funcEv" data-proj="qtbase" >d_func</a>()-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::threadData" title='QObjectPrivate::threadData' data-ref="QObjectPrivate::threadData" data-proj="qtbase" >threadData</a>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qthread_p.h.html#QThreadData::threadId" title='QThreadData::threadId' data-ref="QThreadData::threadId" data-proj="qtbase" >threadId</a>;

        <i>// determine if this connection should be sent immediately or</i>
<i>        // put into the event queue</i>
        <b>if</b> ((<span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::connectionType" title='QObjectPrivate::Connection::connectionType' data-ref="QObjectPrivate::Connection::connectionType" data-proj="qtbase" >connectionType</a> == <span class="namespace">Qt::</span><a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qnamespace.h.html#Qt::ConnectionType::AutoConnection" title='Qt::ConnectionType::AutoConnection' data-ref="Qt::ConnectionType::AutoConnection" data-proj="qtbase" >AutoConnection</a> &amp;&amp; !<span class="local col6 ref" title='receiverInSameThread' data-ref="16receiverInSameThread" >receiverInSameThread</span>)
            || (<span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::connectionType" title='QObjectPrivate::Connection::connectionType' data-ref="QObjectPrivate::Connection::connectionType" data-proj="qtbase" >connectionType</a> == <span class="namespace">Qt::</span><a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qnamespace.h.html#Qt::ConnectionType::QueuedConnection" title='Qt::ConnectionType::QueuedConnection' data-ref="Qt::ConnectionType::QueuedConnection" data-proj="qtbase" >QueuedConnection</a>)) {
            <i>/* Will basically copy the argument and post an event */</i>
            <a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.cpp.html#_ZL15queued_activateP7QObjectiPN14QObjectPrivate10ConnectionEPPv" title='queued_activate' data-ref="_ZL15queued_activateP7QObjectiPN14QObjectPrivate10ConnectionEPPv" data-proj="qtbase" >queued_activate</a>(<span class="local col5 ref" title='sender' data-ref="5sender" >sender</span>, <span class="local col9 ref" title='signal_index' data-ref="9signal_index" >signal_index</span>, <span class="local col3 ref" title='c' data-ref="13c" >c</span>, <span class="local col8 ref" title='argv' data-ref="8argv" >argv</span>);
            <b>continue</b>;
        } <b>else</b> <b>if</b> (<span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::connectionType" title='QObjectPrivate::Connection::connectionType' data-ref="QObjectPrivate::Connection::connectionType" data-proj="qtbase" >connectionType</a> == <span class="namespace">Qt::</span><a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/global/qnamespace.h.html#Qt::ConnectionType::BlockingQueuedConnection" title='Qt::ConnectionType::BlockingQueuedConnection' data-ref="Qt::ConnectionType::BlockingQueuedConnection" data-proj="qtbase" >BlockingQueuedConnection</a>) {
            <i>/* ... Skipped ... */</i>
            <b>continue</b>;
        }

        <i>/* Helper struct that sets the sender() (and reset it backs when it</i>
<i>         * goes out of scope */</i>
        <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.cpp.html#QConnectionSenderSwitcher" title='QConnectionSenderSwitcher' data-ref="QConnectionSenderSwitcher" data-proj="qtbase" >QConnectionSenderSwitcher</a> <dfn class="local col7 ref" id="17sw" title='sw' data-type='QConnectionSenderSwitcher' data-ref="17sw" >sw</dfn>;
        <b>if</b> (<span class="local col6 ref" title='receiverInSameThread' data-ref="16receiverInSameThread" >receiverInSameThread</span>)
            <span class="local col7 ref" title='sw' data-ref="17sw" >sw</span>.<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.cpp.html#_ZN25QConnectionSenderSwitcher12switchSenderEP7QObjectS1_i" title='QConnectionSenderSwitcher::switchSender' data-ref="_ZN25QConnectionSenderSwitcher12switchSenderEP7QObjectS1_i" data-proj="qtbase" >switchSender</a>(<span class="local col5 ref" title='receiver' data-ref="15receiver" >receiver</span>, <span class="local col5 ref" title='sender' data-ref="5sender" >sender</span>, <span class="local col9 ref" title='signal_index' data-ref="9signal_index" >signal_index</span>);

        <em>const</em> <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate" title='QObjectPrivate' data-ref="QObjectPrivate" data-proj="qtbase" >QObjectPrivate</a>::<a class="typedef" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::StaticMetaCallFunction" title='QObjectPrivate::StaticMetaCallFunction' data-ref="QObjectPrivate::StaticMetaCallFunction" data-proj="qtbase" >StaticMetaCallFunction</a> <dfn class="local col8 ref" id="18callFunction" title='callFunction' data-type='const QObjectPrivate::StaticMetaCallFunction' data-ref="18callFunction" >callFunction</dfn> = <span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::{anonymous}::callFunction" title='QObjectPrivate::Connection::&lt;anonymous union&gt;::callFunction' data-ref="QObjectPrivate::Connection::{anonymous}::callFunction" data-proj="qtbase" >callFunction</a>;
        <em>const</em> <em>int</em> <dfn class="local col9 ref" id="19method_relative" title='method_relative' data-type='const int' data-ref="19method_relative" >method_relative</dfn> = <span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::method_relative" title='QObjectPrivate::Connection::method_relative' data-ref="QObjectPrivate::Connection::method_relative" data-proj="qtbase" >method_relative</a>;
        <b>if</b> (<span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::isSlotObject" title='QObjectPrivate::Connection::isSlotObject' data-ref="QObjectPrivate::Connection::isSlotObject" data-proj="qtbase" >isSlotObject</a>) {
            <i>/* ... Skipped....  Qt5-style connection to function pointer */</i>
        } <b>else</b> <b>if</b> (<span class="local col8 ref" title='callFunction' data-ref="18callFunction" >callFunction</span> &amp;&amp; <span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::method_offset" title='QObjectPrivate::Connection::method_offset' data-ref="QObjectPrivate::Connection::method_offset" data-proj="qtbase" >method_offset</a> &lt;= <span class="local col5 ref" title='receiver' data-ref="15receiver" >receiver</span>-&gt;<a class="virtual ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#117" title='QObject::metaObject' data-ref="_ZNK7QObject10metaObjectEv" data-proj="qtbase" >metaObject</a>()-&gt;<a class="member" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#_ZNK11QMetaObject12methodOffsetEv" title='QMetaObject::methodOffset' data-ref="_ZNK11QMetaObject12methodOffsetEv" data-proj="qtbase" >methodOffset</a>()) {
            <i>/* If we have a callFunction (a pointer to the qt_static_metacall</i>
<i>             * generated by moc) we will call it. We also need to check the</i>
<i>             * saved metodOffset is still valid (we could be called from the</i>
<i>             * destructor) */</i>
            <span class="local col0 ref" title='locker' data-ref="10locker" >locker</span>.<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qmutex.h.html#_ZN12QMutexLocker6unlockEv" title='QMutexLocker::unlock' data-ref="_ZN12QMutexLocker6unlockEv" data-proj="qtbase" >unlock</a>(); <i>// We must not keep the lock while calling use code</i>
            <span class="local col8 ref" title='callFunction' data-ref="18callFunction" >callFunction</span>(<span class="local col5 ref" title='receiver' data-ref="15receiver" >receiver</span>, <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject::Call::InvokeMetaMethod" title='QMetaObject::Call::InvokeMetaMethod' data-ref="QMetaObject::Call::InvokeMetaMethod" data-proj="qtbase" >InvokeMetaMethod</a>, <span class="local col9 ref" title='method_relative' data-ref="19method_relative" >method_relative</span>, <span class="local col8 ref" title='argv' data-ref="8argv" >argv</span>);
            <span class="local col0 ref" title='locker' data-ref="10locker" >locker</span>.<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qmutex.h.html#_ZN12QMutexLocker6relockEv" title='QMutexLocker::relock' data-ref="_ZN12QMutexLocker6relockEv" data-proj="qtbase" >relock</a>();
        } <b>else</b> {
            <i>/* Fallback for dynamic objects */</i>
            <em>const</em> <em>int</em> <dfn class="local col0 ref" id="20method" title='method' data-type='const int' data-ref="20method" >method</dfn> = <span class="local col9 ref" title='method_relative' data-ref="19method_relative" >method_relative</span> + <span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::method_offset" title='QObjectPrivate::Connection::method_offset' data-ref="QObjectPrivate::Connection::method_offset" data-proj="qtbase" >method_offset</a>;
            <span class="local col0 ref" title='locker' data-ref="10locker" >locker</span>.<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qmutex.h.html#_ZN12QMutexLocker6unlockEv" title='QMutexLocker::unlock' data-ref="_ZN12QMutexLocker6unlockEv" data-proj="qtbase" >unlock</a>();
            <a class="member" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#_ZN11QMetaObject8metacallEP7QObjectNS_4CallEiPPv" title='QMetaObject::metacall' data-ref="_ZN11QMetaObject8metacallEP7QObjectNS_4CallEiPPv" data-proj="qtbase" >metacall</a>(<span class="local col5 ref" title='receiver' data-ref="15receiver" >receiver</span>, <a class="type" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject" title='QMetaObject' data-ref="QMetaObject" data-proj="qtbase" >QMetaObject</a>::<a class="enum" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobjectdefs.h.html#QMetaObject::Call::InvokeMetaMethod" title='QMetaObject::Call::InvokeMetaMethod' data-ref="QMetaObject::Call::InvokeMetaMethod" data-proj="qtbase" >InvokeMetaMethod</a>, <span class="local col0 ref" title='method' data-ref="20method" >method</span>, <span class="local col8 ref" title='argv' data-ref="8argv" >argv</span>);
            <span class="local col0 ref" title='locker' data-ref="10locker" >locker</span>.<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/thread/qmutex.h.html#_ZN12QMutexLocker6relockEv" title='QMutexLocker::relock' data-ref="_ZN12QMutexLocker6relockEv" data-proj="qtbase" >relock</a>();
        }

        <i>// Check if the object was not deleted by the slot</i>
        <b>if</b> (<span class="local col1 ref" title='connectionLists' data-ref="11connectionLists" >connectionLists</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.cpp.html#QObjectConnectionListVector::orphaned" title='QObjectConnectionListVector::orphaned' data-ref="QObjectConnectionListVector::orphaned" data-proj="qtbase" >orphaned</a>) <b>break</b>;
    } <b>while</b> (<span class="local col3 ref" title='c' data-ref="13c" >c</span> != <span class="local col4 ref" title='last' data-ref="14last" >last</span> &amp;&amp; (<span class="local col3 ref" title='c' data-ref="13c" >c</span> = <span class="local col3 ref" title='c' data-ref="13c" >c</span>-&gt;<a class="ref" href="http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject_p.h.html#QObjectPrivate::Connection::nextConnectionList" title='QObjectPrivate::Connection::nextConnectionList' data-ref="QObjectPrivate::Connection::nextConnectionList" data-proj="qtbase" >nextConnectionList</a>) != <var>0</var>);
}

</pre>


<h2>Conclusion</h2>

<p>We saw how connections are made and how signals slots are emitted.

What we have not seen is the implementation of <a href="http://woboq.com/blog/new-signals-slots-syntax-in-qt5.html">the new Qt5 syntax</a>,
but that will be for another post.</p>

<p><b>Update:</b> <a href="http://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html">
The part 2 is available</a>. </p>


]]></description></item>
<item><title>Browsing C++ Source Code on the Web</title><link>http://woboq.com/blog/codebrowser-introduction.html</link><pubDate>Tue, 18 Sep 2012 19:00:00 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>As a developer, I write code, but I also read a lot of code. Often the code of other people.
It is easy to get lost among all the functions, objects or files. What calls what? What does this
function exactly do? Where is this variable modified?
It is important that as much information as possible can be presented or easily accessible.
</p>
    <p>
Good IDEs are good at displaying that information and ease the navigation in the source code.
But often, I want to browse source code which I don't necessarily have on my hard drive.
While I look at code on the web, I am very disturbed by the poor browsing experience.
This is why I developed an <a href="http://code.woboq.org">online code browser</a>.</p>
</div>
<h2>Introducing the <a href="http://code.woboq.org">Woboq Codebrowser</a>
</h2>
<p>Inspired by the UI of <a href="http://kdevelop.org/">KDevelop</a> (my favorite IDE) and 
using <a href="http://clang.llvm.org/">clang</a> as a parser, I was able to imitate the KDevelop UI.
But there is also a Qt Creator skin, for those who like it sober.</p>
<p>
    <a href="http://code.woboq.org/qt5/qtbase/src/widgets/itemviews/qtreeview.cpp.html#954">
        <img alt="Screenshot with KDevelop style" src="http://woboq.com/blog/codebrowser-introduction/codebrowser_kdevelop.png" style="margin:0.5ex; box-shadow: 1px 1px 2px 2px #ccc;"/>
        <img alt="screenshot with QtCreator style" src="http://woboq.com/blog/codebrowser-introduction/codebrowser_qtcreator.png" style="margin:0.5ex; box-shadow: 1px 1px 2px 2px #ccc;"/>
    </a>
</p>
<p>The idea is a bit based on <a href="http://en.wikipedia.org/wiki/LXR_Cross_Referencer">LXR</a>
or Mozilla's <a href="https://wiki.mozilla.org/DXR">DXR</a>.
But the goal is more to give better visualization and browsing experience rather than a search tool.</p>
<h3>Semantic highlighting</h3>
<p>Once you have tasted the <a href="http://zwabel.wordpress.com/2009/01/08/c-ide-evolution-from-syntax-highlighting-to-semantic-highlighting/">semantic highlighting</a>,
 you cannot go back to non properly highlighted code.</p>
<p>In this screen shot one can see the KDevelop color scheme.
Green for types, dark yellow for members of the current class.
Light color for local variables,  with different color depending on the variable, allows you to quickly recognize what is what.
Virtual methods are in italic.</p>
<p>When you hover over a symbol, all its use gets highlighted.</p>
<h3>Navigation</h3>
<p>
Click on a symbol brings you to the definition of this symbol.  You can browse code like you browse web.
Open links in new tabs or go back in your browser history.
</p>
<h3>Tooltips</h3>
<p>
    <a href="http://code.woboq.org/qt5/qtbase/src/widgets/widgets/qcombobox.cpp.html#3030">
        <img alt="Tooltip" src="http://woboq.com/blog/codebrowser-introduction/tooltip.png" style="margin:0.5ex; box-shadow: 1px 1px 2px 2px #ccc;"/>
    </a>
</p>
<p>
That's where it is getting interesting:
Most of the symbols have a tooltip reminding you of the type of the symbol. The name of the arguments of the function,
and even its default arguments.
It will show what it thinks might be the documentation for a given symbol directly in the tooltip.
</p>
<p>You can also can see the locations where a given function or variable is used.
And if you click on it you get redirected to the right location. </p>
<h2>Browse code now!</h2>
<p>
    <a href="http://woboq.com">Woboq</a> is hosting the code of some stuff which we find useful:
<a href="http://code.woboq.org/qt5/">Qt5</a> (contains V8, JavascriptCore, ...),
<a href="http://code.woboq.org/kde/qt4/">Qt4</a>, <a href="http://code.woboq.org/qt5/qt-creator/">Qt creator</a>,
<a href="http://code.woboq.org/kde/">KDE</a> (most of the modules,
        plus some extra like <a href="http://code.woboq.org/kde/quassel/src/">Quassel</a>),
 <a href="http://code.woboq.org/userspace/llvm/">LLVM/Clang</a>, <a href="http://code.woboq.org/linux/linux/">the linux kernel</a>,
 <a href="http://code.woboq.org/userspace/glibc/">glibc</a>.</p>
<p>So if you ever wanted to look deeper in the implementation of some of your program,
    visit <a href="http://code.woboq.org">http://code.woboq.org</a>.</p>
<h3>Technical Details</h3>
<p>The HTML pages are generated using a tool that use the clang library from the LLVM project.
It parses the code as if it was compiling it, and visit the AST to annotate every token, and build an index of the uses and definitions.</p>
<p>It currently handles C++ and C.<br/>
I did not spend much time on template, or on the preprocessor (macros).  So it is still not as good
as KDevelop in this respect.
</p>
<p>
    <a href="mailto:contact@woboq.com">Contact us</a> if you are interested to use it for your own sources.
</p>
<p>
    <b>Update:</b>
    <a href="http://woboq.com/codebrowser.html">The source code and licence plan are now available</a>.</p>
]]></description></item>
<item><title>UTF-8 processing using SIMD (SSE4)</title><link>http://woboq.com/blog/utf-8-processing-using-simd.html</link><pubDate>Thu, 26 Jul 2012 18:00:00 GMT</pubDate><description><![CDATA[
<div class = "intro">
<p>
<a href="http://en.wikipedia.org/wiki/SIMD">SIMD</a>: "Single instruction, multiple data"
is a class of instructions present in many CPUs today.
For example, on the Intel CPU they are known under the <a href="http://en.wikipedia.org/wiki/Streaming_SIMD_Extensions">SSE</a> acronym.
Those instructions enable more parallelism by operating simultaneously on multiple data.
</p>
<p>In this blog post I will present a method for converting UTF-8 text to UTF-16 using SSE4 compiler intrinsics.
My goal is also to introduce you to the SIMD intrinsics, if you are not familiar with them yet.</p>
</div>


<h2>About Intrinsics</h2>

<p>
CPUs can parallelize computations by using specials instructions that operate simultaneously
on multiples values.
There are large registers that contain <em>vectors</em> of values.
For example, the SSE registers are 128 bits vectors
that can  contain either 2 double, 4 float, 4 int, 8 short or up to 16 char values.
Then, one single instruction can add, substract, multiply, ... all those values and put the
result in another vector register.
<br />
This is called <em>SIMD</em> for Single Instruction Multiple Data.
</p>

<p>Compilers can sometimes automatically vectorize the contents of a simple loop,
but they are not really good at it. If the loop is too complex
or if it depends on the previous iteration, the compiler will fail to vectorize.
(Even if it would be obvious for an human). The vectorization therefore has to be done manually.</p>
<p>
This is where <a href="http://en.wikipedia.org/wiki/Intrinsic_function">compiler intrinsics</a>
help us. They are special functions handled directly in the compiler who will emit the instruction we want.
</p>
<p>The problem with intrinsics is that they are not really portable. They target a specific architecture.
This means you need to write your algorithms for the different CPU architectures you target.
Fortunately, the main compilers use the same intrinsics
 so they are portable across compilers and operating systems.
</p>
<p>You are supposed to detect the support of the instruction set at run-time.
What is usually done is to write several variants of the function for the different target architecture
 and have a function pointer that is set to the best variant for the running architecture.
</p>

 <p>The best documentation I could find is
 <a href="http://msdn.microsoft.com/en-us/library/26td21ds">the reference on MSDN</a>.
 You will have to browse it a bit to see what the available intrinsics are. </p>


<h2>The Task: Converting UTF-8 to UTF-16</h2>

<p>I got interested in SIMD when <a href="http://www.linkedin.com/in/benjaminpoulain">Benjamin</a> was using them to speed up
 <a href="http://code.woboq.org/kde/qt4/src/corelib/tools/qstring.cpp.html#_ZN7QString17fromLatin1_helperEPKci">QString::fromLatin1</a>,
 which  converts a <code>char*</code> encoded in
 <a href="http://en.wikipedia.org/wiki/Latin1">Latin-1</a> to
 <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> (QString's internal encoding).
 After he explained to me how it works, I was able to speed up some of the drawing code inside Qt.
 <br/>
 However in Qt5, we
 <a href="http://www.macieira.org/blog/2012/05/source-code-must-be-utf-8-and-qstring-wants-it/">
 changed the default string encoding</a> from Latin-1 to UTF-8.
</p><p>
 <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> can represent all of Unicode
 while  Latin-1 can only represent the alphabet of a few latin based languages.
     UTF-8 parsing is much more difficult to vectorize because
     a single code point can be encoded by a variable number of bytes.</p>


 <p>
This table explains the correspondence between the bits in UTF-8 and UTF-16:
</p>

<table border="1">
<tr><th></th><th>UTF-8</th><th>UTF-16</th></tr>
<tr><td>ASCII (1 byte)</td>
                  <td><code>0<span style="color:#d00">aaaaaaa</span></code></td>
                  <td><code>00000000 0<span style="color:#d00">aaaaaaa</span></code></td>
</tr>

<tr><td rowspan="2">Basic Multilingual Plane<br/>(2 or 3 bytes)</td>
                <td><code>110<span style="color:#070">bbb</span><span style="color:#0c0">bb</span>
                              10<span style="color:#d00">aaaaaa</span></code></td>
                  <td><code>00000<span style="color:#070">bbb</span>
                            <span style="color:#0c0">bb</span><span style="color:#d00">aaaaaa</span></code></td>

</tr>
<tr>
                <td><code>1110<span style="color:#00d">cccc</span>
                              10<span style="color:#070">bbbb</span><span style="color:#0c0">bb</span>
                              10<span style="color:#d00">aaaaaa</span></code></td>
                  <td><code><span style="color:#00d">cccc</span><span style="color:#070">bbbb</span>
                            <span style="color:#0c0">bb</span><span style="color:#d00">aaaaaa</span></code></td>   
</tr>
<tr><td>Supplementary Planes <br/> (4 bytes)</td>
                 <td><code>11110<span style="color:#d0d">ddd</span>
                              10<span style="color:#d0d">dd</span><span style="color:#00d">cccc</span>
                              10<span style="color:#0a8">bb</span><span style="color:#070">bb</span><span style="color:#0c0">bb</span>
                              10<span style="color:#d00">aaaaaa</span></code> <br/>
                              <code><span style="color:#ba0">uuuu</span> = <span style="color:#d0d">ddddd</span> - 1</code> </td>
                  <td><code>110110<span style="color:#ba0">uu uu</span><span style="color:#00d">cccc</span><span style="color:#0a8">bb</span> <br/>
                            110111<span style="color:#070">bb</span>
                            <span style="color:#0c0">bb</span><span style="color:#d00">aaaaaa</span></code></td>
</tr>
</table>


 <p>I was wondering if we could improve QString::fromUtf8 using SIMD. <br/>
 
Most of the strings are just ASCII which is easy to vectorize,
but I wanted to also try to go ahead and vectorize the more complicated cases as well.<br/>
However, the 4 bytes sequences (Supplementary Planes) are very rarely used
(most used languages and useful symbols are already in the Basic Multilingual Plane)
and also more complicated so I did not vectorize that case for
the scope of this blog post.
This is left as an exercise for the reader ;-)</p>

<h2>Previous work</h2>

<p>UTF-8 processing is a very common task. I was expecting that the problem would be already solved.
Currently however most libraries and applications still have a scalar implementation.
Few  use vectorization, but only for ASCII.</p>
<p>There is a library called <a href="http://u8u16.costar.sfu.ca/">u8u16</a>.
It uses a clever technique by separating the bits in individual vectors.
It is processing 128 char at the time in 8 different vectors.<br/>
I wanted to try a different approach and work directly on one vector.
   Working with 16 char at the time allows speeding up the processing of
    smaller strings.</p>


<h2>The Easy Case: ASCII</h2>

<p>I'm going to start by explaining the simple case when we only
have ASCII. This is very easy to vectorize because for ASCII one byte in UTF-8
is always one byte in UTF-16 with <code>\0</code> bytes in between.<br/>
ASCII is also a very common encoding so it make sense to have a special case for it.</p>

<p>I will start by showing the code and then explaining it</p>

<p>Our function takes a pointer <code>src</code> to the UTF-8 buffer of length <code>len</code>,
   and a pointer <code>dst</code> to a buffer of size at least <code>len*2</code>
   where we will store the UTF-16 output. The function returns the size of the UTF-16 output.
   </p>

<pre class="brush: cpp">
int fromUtf8(const char *src, int len, unsigned short *dst) {
  /* We will process the input 16 bytes at a time,
     so the length must be at least 16. */
    while(len &gt;= 16) {

        /* Load 128 bit into a vector register. We use the 'loadu' intrinsic
           where 'u' stands for unaligned. Loading aligned data is much faster,
           but here we don't know if the source is aligned */
        __m128i chunk = _mm_loadu_si128(reinterpret_cast&lt;const __m128i*&gt;(src));

        /* Detect if it is ASCII by looking if one byte has the high bit set. */
        if (!_mm_movemask_epi8(chunk)) {

            // unpack the first 8 bytes, padding with zeros
            __m128i firstHalf = _mm_unpacklo_epi8(chunk, _mm_set1_epi8(0));
            // and store to the destination
            _mm_storeu_si128(reinterpret_cast&lt;__m128i*&gt;(dst), firstHalf); 

            // do the same with the last 8 bytes
            __m128i secondHalf = _mm_unpackhi_epi8 (chunk, _mm_set1_epi8(0));
            _mm_storeu_si128(reinterpret_cast&lt;__m128i*&gt;(dst+8), secondHalf);

            // Advance
            dst += 16;
            src += 16;
            len -= 16;
            continue;
        }

        // handle the more complicated case when the chunk contains multi-bytes
        // ...
    }
    // handle the few remaining bytes using a classical serial algorith
    // ...
}
</pre>

<p>The type <code>__m128i</code> represents a vector of 128 bits.
It is most likely going to be stored in a SSE register.<br/>
Since we don't know the alignment, we load the data with
<code><a href="http://msdn.microsoft.com/en-us/library/f4k12ae8(v=vs.100).aspx">_mm_loadu_si128</a></code>.
There is also the
<code><a href="http://msdn.microsoft.com/en-us/library/atzzad1h.aspx">_mm_load_si128</a></code>
that assumes the memory
is aligned on 16 bytes. Because it is faster to operate on aligned data, some algorithms
sometimes start with a prologue to handle the first bytes until the rest is aligned.
I did not do that here but we could optimize the ASCII processing further by doing so.
</p>

<p>Once we have loaded 16 bytes of data into <code>chunk</code>, we need to check if
it only contains ASCII. Each ASCII byte should have its most significant bit set to 0.
<code><a href="http://msdn.microsoft.com/en-us/library/s090c8fk(v=vs.100).aspx">_mm_movemask_epi8</a></code>
creates a 16bit mask out of most significant bits of our 16 bytes in the vector.
If that mask is 0 we only have ASCII in that vector.</p>

<p>The next operation is to expand with zeroes. We will do what is called <em>unpacking</em>.
The instructions
<code><a href="http://msdn.microsoft.com/en-us/library/t5h7783k">_mm_unpackhi_epi8</a></code>
and <code><a href="http://msdn.microsoft.com/en-us/library/xf7k860c">_mm_unpacklo_epi8</a></code>
are going to interleave two vectors.
Because the result of an unpack is on 32 bytes, there is two operations:
one to get the first 16 high bytes,
and the other to get the low bytes.<br/>
<code><a href="http://msdn.microsoft.com/en-us/library/x0cx8zd3.aspx">_mm_set1_epi8(0)</a></code> creates a vector filled with zeroes.</p>

<img src="http://woboq.com/blog/utf-8-processing-using-simd/unpack.png" />

<p>Note that vectors are in little endian, so I show the least significant bytes first</p>

<p>Now, we can just store the result with
<code><a href="http://msdn.microsoft.com/en-us/library/w1k1k29t">_mm_storeu_si128</a></code>.
We use the unaligned operation again.</p>

<h2>General Algorithm</h2>

<p>Now that I have introduced you to the ASCII decoding process, we can move on to the general case,
in which we might have multiple bytes for one character. </p>

<p>The algorithm proceeds with the following steps:</p>

<ol>
<li>First, we will <b>classify</b> each bytes so we know where the values in the sequence are and
    how long they are.  This information will be stored in vectors that we can use to mask
    so operations we do later operate only on a certain category of bytes.    
</li>
<li>Then, we will <b>operate on the data</b> to to find the actual Unicode value behind
    each character.  They will be stored at the location of the last byte of a sequence,
    into two different vectors: one for the low bits and one for the high bits.
    </li>
<li>Then we need to <b>shuffle</b> the vectors to remove the
  possible "gaps" left by multi-bytes sequences.
  </li>
<li> Finally, we can store the result and <b>advance</b> the pointers.</li>
</ol>

<p>I will explain every step in more detail.</p>

<p>In our example, I will decode the string
<em>x<span
style="color:#070">≤</span>(<span
style="color:#800">α</span>+<span
style="color:#800">β</span>)<span style="color:#009">²</span><span
style="color:#800">γ</span><span style="color:#009">²</span></em>,
which is represented in UTF-8 as
<code>x<span
style="color:#070">\e2\89\a4</span>(<span style="color:#800">\ce\b1</span>+<span
style="color:#800">\ce\b2</span>)<span
style="color:#009">\c2\b2</span><span style="color:#800">\ce\b3</span><span
style="color:#009">\c2\b2</span></code>.
The "≤" is represented by 3 bytes, the Greek letters by two bytes,
and the "²" also by two bytes. The total length is 17 bytes, so the last byte
will be truncated when loaded into the vector</p>
<h2>Classification</h2>


<p>At the end of this step, we will have the following vectors:</p>
<ul>
<li><b><code>mask</code></b> tells which bit needs to be set to 0 in order to only keep the bits
   that are going to end up in the Unicode value.
   Bits of mask that are set will be unset from the data.</li>
<li><b><code>count</code></b> is zero if the corresponding byte is ASCII or a continuation byte.
 If the corresponding byte is starting a sequence, then it is the number of bytes in that sequence.
 </li>

 <li><b><code>counts</code></b> represents (for each byte) how many bytes are remaining in this sequence.
 It is 0 for ASCII, 1 for the last byte in a sequence, and so on.</li>
</ul>


<p>We start by finding <code>count</code> and <code>mask</code>.
 I do that by computing a vector
  that I called <code>state</code>, in which the 5 higher bits are the mask and the
   3 lower bits represent the count.
</p>

<img src="http://woboq.com/blog/utf-8-processing-using-simd/classification.png" />

<p>We will use the
<code><a href="http://msdn.microsoft.com/en-us/library/9s46csht">_mm_cmplt_epi8</a></code> instruction.
It compares two vectors of 16 signed char,
and returns a mask vector where each byte is equal to <code>0xff</code>
 or <code>0x00</code> depending of the result of the comparison between
 the corresponding chars.
 <br/>We can then use this mask as input to the
 <code><a href="http://msdn.microsoft.com/en-us/library/bb514064">_mm_blendv_epi8</a></code>
  SSE4 instruction.
 It takes 3 input arguments: two vectors and a mask. It returns a vector that has
  the bytes of the second input where the most significant bit of the corresponding byte of the mask is one
  and the bytes of the first input otherwise.
  In other words, for each 16 bytes of the vectors, we have: <br/>
 <code>output[i] = mask[i] &amp; 0x80 ? input2[i] : input1[i]</code></p>

<p>The problem of <code>_mm_cmplt_epi8</code> is that it only works on signed bytes.
That is why we add <code>0x80</code> to everything simulate unsigned comparison.</p>



<pre class="brush: cpp">
    // The state for ascii or contiuation bit: mask the most significant bit.
    __m128i state = _mm_set1_epi8(0x0 | 0x80);

    // Add an offset of 0x80 to work around the fact that we don't have
    // unsigned comparison
    __m128i chunk_signed = _mm_add_epi8(chunk, _mm_set1_epi8(0x80));

    // If the bytes are greater or equal than 0xc0, we have the start of a
    // multi-bytes sequence of at least 2.
    // We use 0xc2 for error detection, see later.
    __m128i cond2 = _mm_cmplt_epi8( _mm_set1_epi8(0xc2-1 -0x80), chunk_signed);

    state = _mm_blendv_epi8(state , _mm_set1_epi8(0x2 | 0xc0),  cond2);

    __m128i cond3 = _mm_cmplt_epi8( _mm_set1_epi8(0xe0-1 -0x80), chunk_signed);

    // We could optimize the case when there is no sequence logner than 2 bytes.
    // But i did not do it in this version.
    //if (!_mm_movemask_epi8(cond3)) { /* process max 2 bytes sequences */ }

    state = _mm_blendv_epi8(state , _mm_set1_epi8(0x3 | 0xe0),  cond3);
    __m128i mask3 = _mm_slli_si128(cond3, 1);

    // In this version I do not handle sequences of 4 bytes. So if there is one
    // we break and do a classic processing byte per byte.
    __m128i cond4 = _mm_cmplt_epi8(_mm_set1_epi8(0xf0-1 -0x80), chunk_signed);
    if (_mm_movemask_epi8(cond4)) { break; }

    // separate the count and mask from the state vector
    __m128i count =  _mm_and_si128(state, _mm_set1_epi8(0x7));
    __m128i mask = _mm_and_si128(state, _mm_set1_epi8(0xf8));

</pre>

<p>From <code>count</code> I will be able to compute <code>counts</code>.
I will use <code><a href="http://msdn.microsoft.com/en-us/library/yadkxc18">_mm_subs_epu8</a></code> which substracts
two vector of unsigned bytes and saturate (so if you underflow, it sets 0).
Then I shift that result, and add it to the count.
Then we do the same, but we substract 2 and shift the result two bytes.</p>
<p><code><a href="http://msdn.microsoft.com/en-us/library/34d3k2kt.aspx">_mm_slli_si128</a></code> shifts a vector on the left by the given number of bytes.
Notice again that we work on little endian.
So that is why I shifted right on the picture, but left in the code.
</p>

<img src="http://woboq.com/blog/utf-8-processing-using-simd/counts.png" />


<pre class="brush: cpp">
    //substract 1, shift 1 byte and add
    __m128i count_subs1 = _mm_subs_epu8(count, _mm_set1_epi8(0x1));
    __m128i counts = _mm_add_epi8(count, _mm_slli_si128(count_subs1, 1));

    //substract 2, shift 2 bytes and add
    counts = _mm_add_epi8(counts, _mm_slli_si128(
                    _mm_subs_epu8(counts, _mm_set1_epi8(0x2)), 2));
</pre>

<h2>Processing</h2>

<p>The goal of this step is to end up with the final unicode bytes values.
They will be split into two vectors (one for the high bytes and one for the low bytes).
We keep them in the location of the last byte of a sequence,
which means that there will be "gaps" in the vector.
</p>

<img src="http://woboq.com/blog/utf-8-processing-using-simd/processing.png" />

<p>There is no instructions that shift the whole vector by an arbitrary
number of bits. It is only possible to shift by an integer number of bytes with
<code>_mm_slli_si128</code> or <code>_mm_srli_si128</code>.
The instructions that shift by an abitrary number of bits only work on vector
with elements of 16 or 32 bits. No 8 bits elements.
We will use what we have and will first shift by one byte (in
<code>chunk_right</code>) and then shift and mask to get what we want.</p>


<pre class="brush: cpp">
    // Mask away our control bits with ~mask (and not)
    chunk = _mm_andnot_si128(mask , chunk);
    // from now on, we only have usefull bits

    // shift by one byte on the left
    __m128i chunk_right = _mm_slli_si128(chunk, 1);

    // If counts == 1,  compute the low byte using 2 bits from chunk_right
    __m128i chunk_low = _mm_blendv_epi8(chunk,
                _mm_or_si128(chunk, _mm_and_si128(
                    _mm_slli_epi16(chunk_right, 6), _mm_set1_epi8(0xc0))),
                _mm_cmpeq_epi8(counts, _mm_set1_epi8(1)) );

    // in chunk_high, only keep the bits if counts == 2
    __m128i chunk_high = _mm_and_si128(chunk ,
                                       _mm_cmpeq_epi8(counts, _mm_set1_epi8(2)));
    // and shift that by 2 bits on the right.
    // (no unwanted bits are comming because of the previous mask)
    chunk_high = _mm_srli_epi32(chunk_high, 2);

    // Add the bits from the bytes for which counts == 3
    __m128i mask3 = _mm_slli_si128(cond3, 1); //re-use cond3 (shifted)
    chunk_high = _mm_or_si128(chunk_high, _mm_and_si128(
        _mm_and_si128(_mm_slli_epi32(chunk_right, 4), _mm_set1_epi8(0xf0)),
                              mask3));
</pre>


<h2>Shuffle</h2>

<p>Now, we need to get rid of the gaps in our strings.
We will start by computing, for each byte, the number of bytes we need to shift.

We notice that <code>count_subs1</code>is the number of bytes we need to skip
for a given sequence.
We will then accumulate all those number in order to get the number of bytes
we need to shift each bytes. Then we reset to zero all the bytes that are supposed
to go away.
</p>
<img src="http://woboq.com/blog/utf-8-processing-using-simd/accumulate.png" />

<pre class="brush: cpp">
    __m128i shifts = count_subs1;
    shifts = _mm_add_epi8(shifts, _mm_slli_si128(shifts, 2));
    shifts = _mm_add_epi8(shifts, _mm_slli_si128(shifts, 4));
    shifts = _mm_add_epi8(shifts, _mm_slli_si128(shifts, 8));

    // keep only if the corresponding byte should stay
    // that is, if counts is 1 or 0  (so &lt; 2)
    shifts  = _mm_and_si128 (shifts , _mm_cmplt_epi8(counts, _mm_set1_epi8(2)));
</pre>

<p>We will shift the <code>shift</code> vector so the meaning of it becomes
the number of bytes that are separating a byte in its final location from
the byte in its original location.
</p>
<p> The maximum we can shift is 10 (if everything is a 3 bytes sequence).
We can then compute in 4 steps.<br/>
We will shift the interesting bit of the vector <code>shift</code>, so it can be used
to control the blend operation.</p>

<pre class="brush: cpp">

        shifts = _mm_blendv_epi8(shifts, _mm_srli_si128(shifts, 1),
                                 _mm_srli_si128(_mm_slli_epi16(shifts, 7) , 1));

        shifts = _mm_blendv_epi8(shifts, _mm_srli_si128(shifts, 2),
                                 _mm_srli_si128(_mm_slli_epi16(shifts, 6) , 2));

        shifts = _mm_blendv_epi8(shifts, _mm_srli_si128(shifts, 4),
                                _mm_srli_si128(_mm_slli_epi16(shifts, 5) , 4));

        shifts = _mm_blendv_epi8(shifts, _mm_srli_si128(shifts, 8),
                                 _mm_srli_si128(_mm_slli_epi16(shifts, 4) , 8));

</pre>

<img src="http://woboq.com/blog/utf-8-processing-using-simd/shift.png" />

<p>Then we can then know, for each byte in the final vector, its
   location in the original vector.  With that information, we can use
   <code><a href="http://msdn.microsoft.com/en-us/library/bb531427.aspx">_mm_shuffle_epi8</a></code>
    (SSSE3) to shuffle the vector and remove the
   "gaps".  Then we can unpack the result and store it, and we are almost done.</p>

<img src="http://woboq.com/blog/utf-8-processing-using-simd/shuffle.png" />

<img src="http://woboq.com/blog/utf-8-processing-using-simd/shuffle2.png" />

<pre class="brush: cpp">
    __m128i shuf = _mm_add_epi8(shifts,
            _mm_set_epi8(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0));

    // Remove the gaps by shuffling
    shuffled_low = _mm_shuffle_epi8(chunk_low, shuf);
    shuffled_high = _mm_shuffle_epi8(chunk_high, shuf);

    // Now we can unpack and store
    __m128i utf16_low = _mm_unpacklo_epi8(shuffled_low, shuffled_high);
    __m128i utf16_high = _mm_unpackhi_epi8(shuffled_low, shuffled_high);
    _mm_storeu_si128(reinterpret_cast&lt;__m128i*&gt;(dst), utf16_low);
    _mm_storeu_si128(reinterpret_cast&lt;__m128i*&gt;(dst+8) , utf16_high);
</pre>

<h2>Error Detection</h2>
<p>So far we have only considered valid UTF-8.  But a conform UTF-8 decoder
 should also handle broken UTF-8. It should detect the following error cases:</p>

 <ol><li>Not enough, misplaced or too many continuation characters.</li>

    <li>Overlong forms: If a sequence decodes to a value that could have been encoded in a shorter sequence.
        For example the quote must be encoded in its ASCII form (<code>\22</code>)
        and not in a multi-byte sequence (<code>\c0\a2</code> or <code>\e0\80\a2</code>).
        Not forbidding those forms could lead to security problems,
        e.g. if the the quote where escaped in the utf-8 input string, but appears again later when decoded.
        </li>

    <li>Invalid or reserved Unicode code point
    (for example, the one reserved for UTF-16 surrogates)</li>
    </ol>

  
<p>Since error is not the common case, what I do in that case is to break, and let
 the rest be handled by the sequential algorithm (Just like when we have 4 bytes sequences).</p>


<pre class="brush: cpp">

    // ASCII characters (and only them) should have the
    // corresponding byte of counts equal 0.
    if (asciiMask ^ _mm_movemask_epi8(_mm_cmpgt_epi8(counts, _mm_set1_epi8(0))))
            break;

    // The difference between a byte in counts and the next one should be negative,
    // zero, or one. Any other value means there is not enough continuation bytes.
    if (_mm_movemask_epi8(_mm_cmpgt_epi8(_mm_sub_epi8(_mm_slli_si128(counts, 1),
                counts), _mm_set1_epi8(1))))
            break;

    // For the 3 bytes sequences we check the high byte to prevent
    // the over long sequence (0x00-0x07) or the UTF-16 surrogate (0xd8-0xdf)
    __m128i high_bits = _mm_and_si128(chunk_high, _mm_set1_epi8(0xf8));
    if (!_mm_testz_si128(mask3,
                _mm_or_si128(_mm_cmpeq_epi8(high_bits,_mm_set1_epi8(0x00)) ,
                            _mm_cmpeq_epi8(high_bits,_mm_set1_epi8(0xd8))) ))
        break;

    // Check for a few more invalid unicode using range comparison and _mm_cmpestrc
    const int check_mode = _SIDD_UWORD_OPS | _SIDD_CMP_RANGES;
    if (_mm_cmpestrc( _mm_cvtsi64_si128(0xfdeffdd0fffffffe), 4,
                     utf16_high, 8, check_mode) |
        _mm_cmpestrc( _mm_cvtsi64_si128(0xfdeffdd0fffffffe), 4,
                      utf16_low, 8, check_mode))
            break;
</pre>

<h2>Advance Pointers</h2>

<p>Now we are almost done.  We just need to advance the source and destination pointers.
The source pointer usually advance by 16, unless it ends in the middle of a sequence.
In that case, we need to roll back 1 or 2 chars. For that,  we look at the end of the
<code>counts</code> vector.<br/>
Then we can see how much we need to advance the destination by looking at the
end of the shift vector.
</p>
<img src="http://woboq.com/blog/utf-8-processing-using-simd/advance.png" />

<pre class="brush: cpp">
    int s = _mm_extract_epi32(shifts, 3);
    int dst_advance = source_advance - (0xff &amp; (s &gt;&gt; 8*(3 - 16 + source_advance)));

    int c = _mm_extract_epi16(counts, 7);
    int source_advance = !(c &amp; 0x0200) ? 16 : !(c &amp; 0x02) ? 15 : 14;

    dst += dst_advance;
    src += source_advance;
</pre>


<h2>Putting it all together</h2>
<p>Now we are done, you can see the result
<a href="https://github.com/woboq/utf8sse4/blob/master/fromutf8-sse.cc">
 there</a>
</p>
<p>I mixed all the operations to limit the dependencies between the operations that are
next to each other to achieve better pipeline performance.
I am surprised that the compiler did not do that for me.</p>

<h2>Benchmarks Results</h2>


<table border="1">
<tr><th/><th>Long Chinese text (8KiB)</th><th>36 bytes of chinese text</th>
                                                         <th>Long ASCII (24KiB)</th>  <th>20 ASCII bytes</th></tr>
<tr><th>Iconv</th> <td>62000ns</td> <td>380ns</td>         <td>165000ns</td>       <td>230ns</td>   </tr>
<tr><th>Qt (scalar)</th> <td>43000ns</td>  <td>180ns</td> <td>55000ns</td>      <td>67ns</td></tr>
<tr><th>u8u16</th>  <td>20000ns</td>  <td>300ns</td>     <td>8000ns</td>          <td>37ns</td> </tr>
<tr><th>This solution (SSE4.1)</th> <td>22000ns</td><td>110ns</td>  <td>15000ns</td>  <td>40ns</td></tr>   </table>

<img src="http://woboq.com/blog/utf-8-processing-using-simd/graph.png" />

<p>We beat u8u16 on small strings but it is better on large strings because
it processes more bytes at the same time. We are still better than any
scalar processing. 
</p>


<p>I added some debug output in the implementation of <code>QString::fromUtf8</code>
in Qt 4.8 and ran few KDE applications translated in French.
The average size of strings that goes through this function is 9 characters.
More than 50% of the string are less than 2 character long, 85% are less than 16,
and 13% are between 16 and 128 characters long.
98% of the strings where only composed of ASCII. The rest was mainly having
2 bytes sequences and very few 3 bytes sequences.  There is no sequence of 4 bytes.<br/>
Also consider that the processing of UTF-8 is probably far from being the bottleneck
of any application that does something useful.</p>
<p>So was my exercise useless? Maybe in practice, but I think there is still
something to learn from this that can be applied to another algorithm that might
be a bottleneck.</p>

]]></description></item>
<item><title>We are now offering Quassel IRC Hosting</title><link>http://woboq.com/blog/quasselcore-hosting-by-woboq.html</link><pubDate>Sat, 07 Jul 2012 10:12:31 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>
In an attempt to bring the things we like to you, we are offering accounts
on our <a href="http://woboq.com/quassel.html">Woboq Quasselcore</a>.</p>
</div>
<p>

In case you have not
heard of Quassel before: <a href="http://www.quassel-irc.org/">Quassel</a> is a distributed IRC client where the
Quassel core stays connected to your IRC channels and you can use any of your
computers to connect to the core and have your chat history accessible.
</p>
<p>
 To find our more, check out our <a href="http://woboq.com/quassel.html">Woboq Quassel Hosting</a> page
 or visit us on #woboquassel on irc.freenode.net.
</p>
<center>
    <img src="http://woboq.com/blog/quasselcore-hosting-by-woboq/quassel.png"/>
</center>
<p>
As a small side project, we are also trying to bring the Quassel IRC experience
to the iPad. More about this will follow here :-) 
<b>Update:</b>
    <a href="https://itunes.apple.com/app/iquassel/id566844252">Quassel for iPad</a>
has arrived!
</p>
]]></description></item>
<item><title>C++11 in Qt5</title><link>http://woboq.com/blog/cpp11-in-qt5.html</link><pubDate>Mon, 11 Jun 2012 12:00:00 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>
C++11 is the name of the current version of the C++ standard, which brings many new features to the language.
</p>
    <p> Qt 4.8 was the first version of Qt that started to make use of some of the new C++11 features  in its API.
 I wrote a blog post about <a href="http://blog.qt.digia.com/blog/2011/05/26/cpp0x-in-qt/">C++11 in Qt 4.8</a>
  before the 4.8 release which I won't repeat here.</p>
    <p>In Qt5, we make use of even more features. I will go into detail about some of them in
   this post.</p>
</div>
<h2 id="lambda">Lambda expressions for slots</h2>
<p>
    <a href="http://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B">Lambda expressions</a>
 are a new syntax in C++11 which allow to declare anonymous functions.
 Anonymous functions can be used in order to use small functions as parameter
 without requiring to explicitly declare them. <br/>
 The previous way to write <a href="http://en.wikipedia.org/wiki/Function_object#In_C_and_C.2B.2B">functors</a> using
 <tt>operator()</tt> in a struct was requiring a lot of boilerplate code.</p>
<p>It was already possible in Qt 4.8 to use lambda expressions in some QtConcurrent functions. Now it is even possible
 to use them as slots using the
 <a href="http://woboq.com/blog/new-signals-slots-syntax-in-qt5.html">new connect syntax</a>.</p>
<p>
 Remember the time when you had to write a one-line function for your slot.
 Now you can write it right in place.
 It is much more readable to have the function directly where you reference it:</p>
<pre class="brush: cpp">
 connect(sender, &amp;Sender::valueChanged, [=](const QString &amp;newValue) {
        receiver-&gt;updateValue("senderValue", newValue);
    });
</pre>
<p>
Lambda functions are supported since MSVC 2010, GCC 4.5, and clang 3.1.
</p>
<h2 id="unicode">Unicode literal</h2>
<p>In C++11, you can generate UTF-16 by writing <code>u"MyString"</code>.
This is used by Qt to implement
<tt>QStringLiteral</tt> which is a macro that initializes the QString at compile time without run-time overhead.</p>
<pre class="brush: cpp">
    QString someString = QStringLiteral("Hello");
</pre>
<p>See my <a href="http://woboq.com/blog/qstringliteral.html">previous blog about QStringLiteral</a>.</p>
<h2 id="constexpr">Constant expressions: <tt>constexpr</tt>
</h2>
<p>This new <tt>constexpr</tt> C++11 keyword can be added to annotate some inline functions to specify that they
could be computed at compile time.
In Qt 5, we introduced
<a href="http://qt-project.org/doc/qt-5.0/qtglobal.html#Q_DECL_CONSTEXPR">
        <tt>Q_DECL_CONSTEXPR</tt>
    </a>
which is defined to <tt>constexpr</tt> when the compiler supports it, or nothing otherwise.</p>
<p>We also annotated some of the Qt functions that made sense (for example QFlags), which allows them to be used in constant expressions.</p>
<pre class="brush: cpp">
enum SomeEnum { Value1, Value2, Value3 };
Q_DECLARE_OPERATORS_FOR_FLAGS(QFlags&lt;SomeEnum&gt;)
// The previous line declares
// Q_DECL_CONSTEXPR QFlags&lt;SomeValue&gt; operator|(SomeValue,SomeValue) {...}

int someFunction(QFlags&lt;SomeEnum&gt; value) {
    switch (value) {
        case SomeEnum::Value1:
            return 1;
        case SomeEnum::Value2:
            return 2;
        case SomeEnum::Value1 | SomeEnum::Value3:
        // Only possible with C++11 and because QFlags operators are constexpr
        // Previously this line would call
        //        QFlags&lt;SomeValue&gt; operator|(SomeValue,SomeValue)
        // that would have thrown an error because only compiler constants
        // are allowed as case satement

            return 3;
        default:
            return 0;
    }
}
</pre>
<p>(Notice also here that I used <code>SomeEnum::</code> in front of the values, which is allowed in C++11,
     but was not allowed before)</p>
<h2 id="static_assert">static_assert</h2>
<p>C++11 helps producing better error messages when something wrong can be detected at compile time using
<tt>static_assert</tt>.  In Qt5 we introduced the macros <tt>Q_STATIC_ASSERT</tt>, and <tt>Q_STATIC_ASSERT_X</tt>
That will use <tt>static_assert</tt> if available, or some other template trick if not.</p>
<p>Qt uses that macro already quite a lot in order to provide better compiler errors when the API is not used properly.</p>
<h2 id="override_final">Override and final</h2>
<p>Have you ever had code that did not work because you had a typo in the name of a virtual function you re-implemented?
(Or forgot that damn <tt>const</tt> at the end)</p>
<p>You can now annotate the functions that are meant to override virtual functions with <tt>Q_DECL_OVERRIDE</tt>.</p>
<p>That macro will be substituted to the new "override" attribute if the compilers supports it, or to nothing otherwise.
If you compile your code with C++11 enabled compiler you will get an error if you have a typo,
or if you changed a virtual method while re-factoring.</p>
<pre class="brush: cpp">
class MyModel : public QStringListModel {
    //...
protected:
     Qt::ItemFlags flags (const QModelIndex &amp; index)  Q_DECL_OVERRIDE;
};
</pre>
<p>And because we forgot the <tt>const</tt> that will produce errors such as:</p>
<pre>
mymodel.h:15: error: `Qt::ItemFlags MyModel::flags(const QModelIndex&amp;)`
 marked override, but does not override
</pre>
<p>There is also <tt>Q_DECL_FINAL</tt> that is substituted to the <tt>final</tt> attribute which specifies
a virtual function cannot be overridden.</p>
<h2 id="delete">Deleted member</h2>
<p>The new macro <tt>Q_DECL_DELETE</tt> expands to <code>= delete</code> for compilers that support deleted functions.
This us useful to give better compiler errors to avoid common mistakes.</p>
<p>Deleted functions are used to explicitly delete the function that would be otherwise ceated automatically
by the compiler (such as a default constructor, or a copy assignement operator). Deleted functions may not be called
 and a compiler error is thrown if they are used.</p>
<p>
We use it for example in the <tt>Q_DISABLE_COPY</tt> macro.
Before, the trick was to keep those members private, but the error message was not as good.</p>
<h2>Rvalue References and Move Constructors</h2>
<p>In <a href="http://blog.qt.digia.com/blog/2011/05/26/cpp0x-in-qt/">the Qt 4.8 article</a>
I already explained what rvalue references are about.</p>
<p>Due to a change of the internals of the reference counting of our shared class in Qt5, it was possible to
<a href="https://qt.gitorious.org/qt/qtbase/commit/f92fdd190d056fe929f723e3f2ce9e0c0b141cec">add a move constructor
for many of them</a>.</p>
<h2>Conclusion</h2>
<p>MSVC does not require any special flags and enables the C++11 features by default, but GCC or Clang require
<tt>-std=c++0x</tt>.</p>
<p>By default, Qt5 itself will be compiled with the C++11 flags on compilers that need it.</p>
<p> If you use qmake, you can add that line to your <tt>.pro</tt> file (Qt5):</p>
<pre>
CONFIG += c++11
</pre>
<p>(In Qt4, it should be something like: <code>gcc:CXXFLAGS += -std=c++0x</code>)</p>
<p>And now you can enjoy all the nice features of C++11.
(It is already worth doing it only for being able to use <tt>auto</tt>)</p>
]]></description></item>
<item><title>QStringLiteral explained</title><link>http://woboq.com/blog/qstringliteral.html</link><pubDate>Mon, 21 May 2012 09:34:45 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>
        <tt>
            <a href="http://doc-snapshot.qt-project.org/5.0/qstring.html#QStringLiteral">QStringLiteral</a>
        </tt>
 is a new macro introduced in Qt 5 to create QString from string literals.
 (String literals are strings inside <tt>""</tt> included in the source code).
In this blog post, I explain its inner working and implementation.
</p>
</div>
<h2>Summary</h2>
<p>Let me start by giving a guideline on when to use it:<bt/>
If you want to initialize a QString from a string literal in Qt5,
  you should use:</p>
<ul>
    <li>Most of the cases: <code>QStringLiteral("foo")</code> if it will actually be converted to <tt>QString</tt>
    </li>
    <li>
        <code>QLatin1String("foo")</code>  if it is use with a function that has an overload
           for <code>QLatin1String</code>. (such as <code>operator==, operator+, startWith, replace, ...</code>)
        </li>
</ul>
<p>I have put this summary at the beginning for the ones that don't want to read the technical details that follow.</p>
<p>Read on to understand how <tt>QStringLiteral</tt> works</p>
<h2>Reminder on how QString works</h2>
<p>QString, as many classes in Qt, is an implicitly shared class. 
   Its only member is a pointer to the 'private' data.
     The <tt>QStringData</tt> is allocated with malloc, and enough room is allocated after it to put the
     actual string data in the same memory block.
     </p>
<pre class="brush: cpp">
// Simplified for the purpose of this blog
struct QStringData {
  QtPrivate::RefCount ref; // wrapper around a QAtomicInt
  int size; // size of the string
  uint alloc : 31; // amount of memory reserved after this string data
  uint capacityReserved : 1; // internal detail used for reserve()

  qptrdiff offset; // offset to the data (usually sizeof(QSringData))

  inline ushort *data()
  { return reinterpret_cast&lt;ushort *&gt;(reinterpret_cast&lt;char *&gt;(this) + offset); }
};

// ...

class QString {
  QStringData *d;
public:
  // ... public API ...
};
</pre>
<img src="http://woboq.com/blog/qstringliteral/qstringdata.png"/>
<p>The offset is a pointer to the data relative to the <tt>QStringData</tt>. In Qt4, it used to be an actual
pointer. We'll see why it has been changed.</p>
<p>The actual data in the string is stored in UTF-16, which uses 2 bytes per character.</p>
<h3>Literals and Conversion</h3>
<p>Strings literals are the strings that appears directly in the source code, between quotes.
<br/> Here are some examples. (suppose <code>action, string</code>, and <code>filename</code> are <tt>QString</tt>
</p>
<pre class="brush: cpp">
    o-&gt;setObjectName("MyObject");
    if (action == "rename")
        string.replace("%FileName%", filename);
</pre>
<p>In the first line, we call the function
<code>QObject::setObjectName(const QString&amp;)</code>.
There is an implicit conversion from <code>const char*</code> to <tt>QString</tt>, via its constructor.
A new QStringData is allocated with enough room to hold <tt>"MyObject"</tt>, and then the string is
copied and converted from UTF-8 to UTF-16.</p>
<p>The same happens in the last line where the function
<code> QString::replace(const QString &amp;, const QString &amp;)</code> is called. 
A new QStringData is allocated for <tt>"%FileName%"</tt>.</p>
<p>
    <b>Is there a way to prevent the allocation of <tt>QStringData</tt> and copy of the string?</b>
</p>
<p>Yes, one solution to avoid the costly creation of a temporary QString object is to have overload for
common function that takes <code>const char*</code> parameter.<br/>
So we have those overloads for <code>operator==</code>
</p>
<pre class="brush: cpp">
bool operator==(const QString &amp;, const QString &amp;);
bool operator==(const QString &amp;, const char *);
bool operator==(const char *, const QString &amp;) 
</pre>
<p>The overloads do not need to create a new QString object for our literal and can operate directly
on the raw <tt>char*</tt>.</p>
<h3>Encoding and <tt>QLatin1String</tt>
</h3>
<p>In Qt5, we
<a href="http://www.macieira.org/blog/2012/05/source-code-must-be-utf-8-and-qstring-wants-it/">
    changed the default</a> decoding for the <tt>char*</tt> strings to UTF-8.
But many algorithms are much slower with UTF-8 than with plain ASCII or latin1</p>
<p>Hence you can use <code>QLatin1String</code>, which is just a thin wrapper around <code>char *</code>
that specify the encoding. There are overloads taking <code>QLatin1String</code> for functions that can opperate or
the raw latin1 data directly without conversion.</p>
<p>So our first example now looks like:</p>
<pre class="brush: cpp">
    o-&gt;setObjectName(QLatin1String("MyObject"));
    if (action == QLatin1String("rename"))
        string.replace(QLatin1String("%FileName%"), filename);
</pre>
<p>The good news is that <code>QString::replace</code> and <code>operator==</code> have overloads for <tt>QLatin1String</tt>.
So that is much faster now.</p>
<p>In the call to <tt>setObjectName</tt>, we avoided the conversion from UTF-8, but we still have an (implicit) conversion
from <tt>QLatin1String</tt> to <tt>QString</tt> which has to allocate the <tt>QStringData</tt> on the heap.</p>
<h2>Introducing <code>QStringLiteral</code>
</h2>
<p>Is it possible to avoid the allocation and copy of the string literal even for the cases like <code>setObjectName</code>?
Yes, that is what <code>QStringLiteral</code> is doing.</p>
<p>This macro will try to generate the QStringData at compile time with all the field initialized.
   It will even be located in the <tt>.rodata</tt> section, so it can be shared between processes.</p>
<p>We need two languages feature to do that:</p>
<ol>
    <li>
        <em>The possibility to generate UTF-16 at compile time:</em>
        <br/>
        On Windows we can use the wide char <code>L"String"</code>.
        On Unix we are using the new C++11 Unicode literal: <code>u"String"</code>.
        (Supported by GCC 4.4 and clang.)
     </li>
    <li>
        <em>The ability to create static data from expressions.</em>
        <br/>
        We want to be able to put QStringLiteral everywhere in the code.
        One way to do that is to put a <code>static QStringData</code> inside a C++11 lambda expression.
        (Supported by MSVC 2010 and GCC 4.5)
        (<del>And we also make use of the GCC
        <a href="http://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Statement-Exprs.html">
                <code>__extension__ ({ })</code>
            </a>
        </del>
        <em>Update:</em> The support for the GCC extension was removed before the beta because it does not work
            in every context lambas are working, such as in default functions arguments)
       </li>
</ol>
<h2>Implementation</h2>
<p>We will need need a POD structure that contains both the QStringData and the actual string.
  Its structure will depend on the method we use to generate UTF-16.
 </p>
<p>The code bellow was extracted from <a href="http://code.woboq.org/qt5/qtbase/src/corelib/tools/qstring.h.html">qstring.h</a>,
     with added comments and edited for readability.</p>
<pre class="brush: cpp">

/* We define QT_UNICODE_LITERAL_II and declare the qunicodechar
   depending on the compiler */
#if defined(Q_COMPILER_UNICODE_STRINGS)
   // C++11 unicode string
   #define QT_UNICODE_LITERAL_II(str) u"" str
   typedef char16_t qunicodechar;
#elif __SIZEOF_WCHAR_T__ == 2
   // wchar_t is 2 bytes  (condition a bit simplified)
   #define QT_UNICODE_LITERAL_II(str) L##str
   typedef wchar_t qunicodechar;
#else
   typedef ushort qunicodechar; // fallback
#endif

// The structure that will contain the string.
// N is the string size
template &lt;int N&gt;
struct QStaticStringData
{
    QStringData str;
    qunicodechar data[N + 1];
};

// Helper class wrapping a pointer that we can pass to the QString constructor
struct QStringDataPtr
{ QStringData *ptr; };

</pre>
<pre class="brush: cpp">

#if defined(QT_UNICODE_LITERAL_II)
// QT_UNICODE_LITERAL needed because of macro expension rules
# define QT_UNICODE_LITERAL(str) QT_UNICODE_LITERAL_II(str)
# if defined(Q_COMPILER_LAMBDA)

#  define QStringLiteral(str) \
    ([]() -&gt; QString { \
        enum { Size = sizeof(QT_UNICODE_LITERAL(str))/2 - 1 }; \
        static const QStaticStringData&lt;Size&gt; qstring_literal = { \
            Q_STATIC_STRING_DATA_HEADER_INITIALIZER(Size), \
            QT_UNICODE_LITERAL(str) }; \
        QStringDataPtr holder = { &amp;qstring_literal.str }; \
        const QString s(holder); \
        return s; \
    }()) \

# elif defined(Q_CC_GNU)
// Use GCC To  __extension__ ({ }) trick instead of lambda
// ... &lt;skiped&gt; ...
# endif
#endif

#ifndef QStringLiteral
// no lambdas, not GCC, or GCC in C++98 mode with 4-byte wchar_t
// fallback, return a temporary QString
// source code is assumed to be encoded in UTF-8
# define QStringLiteral(str) QString::fromUtf8(str, sizeof(str) - 1)
#endif
</pre>
<p>Let us simplify a bit this macro and look how the macro would expand</p>
<pre class="brush: cpp">
o-&gt;setObjectName(QStringLiteral("MyObject"));
// would expand to: 
o-&gt;setObjectName(([]() {
        // We are in a lambda expression that returns a QStaticString

        // Compute the size using sizeof, (minus the null terminator)
        enum { Size = sizeof(u"MyObject")/2 - 1 };

        // Initialize. (This is static data initialized at compile time.)
        static const QStaticStringData&lt;Size&gt; qstring_literal =
        { { /* ref = */ -1, 
            /* size = */ Size, 
            /* alloc = */ 0, 
            /* capacityReserved = */ 0, 
            /* offset = */ sizeof(QStringData) },
          u"MyObject" };

         QStringDataPtr holder = { &amp;qstring_literal.str };
         QString s(holder); // call the QString(QStringDataPtr&amp;) constructor
         return s;
    }()) // Call the lambda
  );
</pre>
<p>The reference count is initialized to -1.
A negative value is never incremented or decremented
because we are in read only data.</p>
<p>One can see why it is so important to have an offset (<tt>qptrdiff</tt>) rather than
a pointer to the string (<tt>ushort*</tt>) as it was in Qt4.
It is indeed impossible to put pointer in the read only section because
pointers might need to be <a href="http://en.wikipedia.org/wiki/Relocation_(computer_science)">relocated</a>
at load time.
That means that each time an application or library,
the <abbr title="In fact, the loader">OS</abbr> needs to re-write all the pointers addresses using the relocation table.</p>
<h2>Results</h2>
<p>For fun, we can look at the assembly generated for a very simple call to QStringLiteral. We can see that
  there is almost no code, and how the data is laid out in the <tt>.rodata</tt> section</p>
<p>We notice the overhead in the binary. The string takes twice as much memory since it is encoded in UTF-16,
     and there is also a header of <tt>sizeof(QStringData) = 24</tt>.
   This memory overhead is the reason why it still makes sense to still use <tt>QLatin1String</tt>
   when the function you are calling has an overload for it.</p>
<pre class="brush: cpp">
QString returnAString() {
    return QStringLiteral("Hello");
}
</pre>
<p>Compiled with <code>g++ -O2 -S -std=c++0x</code>  (GCC 4.7) on x86_64</p>
<pre class="brush: asm">
    .text
    .globl  _Z13returnAStringv
    .type   _Z13returnAStringv, @function
_Z13returnAStringv:
    ; load the address of the QStringData into %rdx
    leaq    _ZZZ13returnAStringvENKUlvE_clEvE15qstring_literal(%rip), %rdx
    movq    %rdi, %rax
    ; copy the QStringData from %rdx to the QString return object
    ; allocated by the caller.  (the QString constructor has been inlined)
    movq    %rdx, (%rdi)
    ret
    .size   _Z13returnAStringv, .-_Z13returnAStringv
    .section    .rodata
    .align 32
    .type   _ZZZ13returnAStringvENKUlvE_clEvE15qstring_literal, @object
    .size   _ZZZ13returnAStringvENKUlvE_clEvE15qstring_literal, 40
_ZZZ13returnAStringvENKUlvE_clEvE15qstring_literal:
    .long   -1   ; ref
    .long   5    ; size
    .long   0    ; alloc + capacityReserved 
    .zero   4    ; padding
    .quad   24   ; offset
    .string "H"  ; the data. Each .string add a terminal '\0'
    .string "e"
    .string "l"
    .string "l"
    .string "o"
    .string ""
    .string ""
    .zero   4
</pre>
<h2>Conclusion</h2>
<p>I hope that now that you have read this you will have a better understanding on where to use and not to use
<tt>QStringLiteral</tt>.<br/>
There is another macro <tt>QByteArrayLiteral</tt>, which work exactly on the same principle but creates a QByteArray.</p>
<p>
    <em>Update:</em> See also the <a href="http://woboq.com/blog/internals-of-qmutex-in-qt5.html">internals of QMutex</a>
 and <a href="http://woboq.com/blog/cpp11-in-qt5.html">more C++11 features in Qt5</a>.
</p>
]]></description></item>
<item><title>Signals and Slots in Qt5</title><link>http://woboq.com/blog/new-signals-slots-syntax-in-qt5.html</link><pubDate>Thu, 12 Apr 2012 18:12:45 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>
Qt5 alpha has been released.  One of the features which I have been working on is a <a href="http://qt-project.org/wiki/New_Signal_Slot_Syntax">new syntax</a> for signals and slot.
This blog entry will present it.
</p>
</div>
<h1>Previous syntax</h1>
<p>Here is how you would connect a signal to a slot:</p>
<pre class="brush: cpp">
connect(sender, SIGNAL(valueChanged(QString,QString)),
        receiver, SLOT(updateValue(QString)) );
</pre>
<p>What really happens behind the scenes is that the <code>SIGNAL</code> and <code>SLOT</code> macros 
  will convert their argument to a string.
  Then <code>QObject::connect()</code> will compare those strings with the introspection data
  collected by the <tt>moc</tt> tool.
  </p>
<h2>What's the problem with this syntax?</h2>
<p>
  While working fine in general, we can identify some issues:</p>
<ul>
    <li>No compile time check: All the checks are done at run-time by parsing the strings. 
      That means if you do a typo in the name of the signal or the slot, it will compile
      but the connection will not be made, and you will only notice a warning in the standard output.</li>
    <li>Since it operates on the strings, the type names of the slot must match exactly the ones of the
      signal. And they also need to be the same in the header and in the connect statement.
      This means it won't work nicely if you want to use <code>typedef</code> or namespaces</li>
</ul>
<h1>New syntax: using function pointers</h1>
<p>In the upcoming Qt5, an alternative syntax exist.  The former syntax will still work. 
But you can now also use this new way of connecting your signals to your slots:</p>
<pre class="brush: cpp">
connect(sender, &amp;Sender::valueChanged,
        receiver, &amp;Receiver::updateValue );
</pre>
<p>Which one is the more beautiful is a matter of taste.
   One can quickly get used to the new syntax.</p>
<p>So apart from the aesthetic point of view, let us go over some of the things that it brings us:</p>
<h2>Compile-time checking</h2>
<p>You will get a compiler error if you misspelled the signal or slot name,
   or if the arguments of your slot do not match those from the signal.<br/>
   This might save you some time while you are doing some re-factoring and change the
   name or arguments of signals or slots.</p>
<p>An effort has been made, using <tt>static_assert</tt> to get nice compile errors if the arguments do not match or of you miss a <tt>Q_OBJECT</tt>
</p>
<h2>Arguments automatic type conversion</h2>
<p>Not only you can now use <code>typedef</code> or namespaces properly, but you can also connect signals
to slots that take arguments of different types if an implicit conversion is possible</p>
<p>In the following example, we connect a signal that has a <code>QString</code> 
   as a parameter to a slot that takes a <code>QVariant</code>.
   It works because <code>QVariant</code> has an implicit constructor that takes a <code>QString</code>
</p>
<pre class="brush: cpp">
class Test : public QObject 
{ Q_OBJECT
public:
    Test() {
        connect(this, &amp;Test::someSignal, this, &amp;Test::someSlot);
    }
signals:
    void someSignal(const QString &amp;);
public:
    void someSlot(const QVariant &amp;);
};
</pre>
<h2>Connecting to any function</h2>
<p>As you might have seen in the previous example, the slot was just declared as <code>public</code>
and not as <code>slot</code>. Qt will indeed call directly the function pointer of the slot, and
will not need <code>moc</code> introspection anymore. (It still needs it for the signal)</p>
<p>But what we can also do is connecting to any function or functor:</p>
<pre class="brush: cpp">
static void someFunction() {
    qDebug() &lt;&lt; "pressed";
}
// ... somewhere else
    QObject::connect(button, &amp;QPushButton::clicked, someFunction);
</pre>
<p>This can become very powerful when you associate that with boost or <code>tr1::bind</code>.
</p>
<h2>C++11 lambda expressions</h2>
<p>Everything documented here works with the plain old C++98. But if you use compiler that supports
C++11, I really recommend you to use some of the language's new features.
Lambda expressions are supported
by at least MSVC 2010, GCC 4.5, clang 3.1. For the last two, you need to pass <tt>-std=c++0x</tt> as
a flag.</p>
<p>You can then write code like:</p>
<pre class="brush: cpp">
void MyWindow::saveDocumentAs() {
    QFileDialog *dlg = new QFileDialog();
    dlg-&gt;open();
    QObject::connect(dlg, &amp;QDialog::finished, [=](int result) {
        if (result) {
            QFile file(dlg-&gt;selectedFiles().first());
            // ... save document here ...
        }
        dlg-&gt;deleteLater();
    });
}
</pre>
<p>This allows you to write asynchronous code very easily.</p>
<p>
    <em>Update:</em> Also have a look what <a href="http://woboq.com/blog/cpp11-in-qt5.html">other C++11 features Qt5 offers</a>.
</p>
<h1>So what now?</h1>
<p>It is time to try it out. <a href="http://labs.qt.nokia.com/2012/04/03/qt-5-alpha/">Check out the alpha</a> and start playing. Don't hesistate to report bugs.</p>
]]></description></item>
<item><title>On Reviewing a Patch in Qt</title><link>http://woboq.com/blog/reviewing-a-qt-patch.html</link><pubDate>Mon, 23 Jan 2012 17:47:05 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>
While I was working on Qt at Nokia I spent a lot of time
reviewing patches from colleagues.
</p>
    <p>
Peer reviewing is an important step, and there is a reason why we do it in Qt.
<br/>
        <b>Code in libraries (such as Qt) requires much greater care than application code.</b>
        <br/>
The main reason is that you need to maintain compatibility for your users.
You want to avoid regressions in your library, so code that works
continues to work, even if the user did some hack or trick.
For the user of the library, it has great value to be able to upgrade it without
too much effort.
A subtle behaviour difference in the library might introduce a bug in the application
that might be really hard to track in the millions of old lines of code of the application.
<!--The Qt library is used by a lot of software. Each minute spent improving Qt's quality
potentially saves hours days for the developers who use Qt in their software.-->
    </p>
</div>
<p>
Reviewing changes starts by looking for obvious mistakes and incompatibilities
with the project guidelines:
<ul>
        <li>Is the code style correct?</li>
        <li>Is the code (auto)tested?</li>
        <li>Are the new APIs properly documented?</li>
        <li> Does the code follow the project policy? (Thread safety, no static global objects, no exported symbols without prefix,
No use of features not supported by a supported compiler, ...)</li>
    </ul>
But all of this is the <em>least important part of reviewing</em>.
Because the submitter is already supposed to know <a href="http://wiki.qt-project.org/Coding_Conventions">those
policies</a> that should be documented for any software project.
<!--(Sometimes even, some of these compliance are tested automatically, this is the role of the Qt Sanity Bot)-->
</p>
<p>
The hard part of the review is seeing the things that the author of the patch could not possibly know.<br/>
    <b>It takes someone already familiar with the code to do the review.</b>
Someone who knows how the code interacts
with the other parts, someone who knows the rationale behind some of the part of the code.
<br/>
Even if you are familiar with the code, you almost always need to open the IDE
and browse the existing code and the code it interacts too.
Making a review by just looking at the patch may be possible for trivial compilation fix, but in almost
all case of non trivial code, you will need to <b>open the relevant files on your IDE.</b>
</p>
<p>
There is so many things to check and to be aware of: code calling virtual functions, code used
for other use cases than the one of the bug report, ...
<br/>
You also need to think hard about what the patch might break and what the behaviour changes are.
</p>
<p>As an example, let us take someone who does a change in a <tt>QComboBox</tt>
to fix a usability glitch on Windows.
Someone not familiar with <tt>QComboBox</tt>
might not know that it behaves very differently depending on the style.
The reviewer will likely to be able
to spot that a change will "break" that style.
</p>
<p>
Another example is someone who identifies that a bug is caused by one wrong condition in an
<tt>if</tt> clause.
Changing seems to fix the problem. But why was that condition there?
If the code is not commented and the history of the code shows it is very old,
no relevant information can be deduced.
The reviewer should be the one who knows that this condition is there to test a very specific use case that might or might
not be required anymore.
</p>
<p>
Inside Nokia we used to have an internal <a href="http://en.wikipedia.org/wiki/Pastebin">Pastebin</a> website for putting up patches.
Nowadays the Qt Project is using a <a href="http://wiki.qt-project.org/Code_Reviews">much more advanced process for reviewing</a>.
</p>
]]></description></item>
<item><title>Internals of QMutex in Qt 5</title><link>http://woboq.com/blog/internals-of-qmutex-in-qt5.html</link><pubDate>Wed, 21 Dec 2011 18:23:45 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>
You may want to read this blog if you want to understand the internals of QMutex
or if you are interested in lock-free algorithms and want to discover one.
You do not need to read or understand this article if you just want to use QMutex
in your application.
I found implementing QMutex interesting and therefore I want to share the knowledge.
</p>
    <p>
I am going to show and explain a simplified version of the real code.
If you want to see the real code, you can just browse the Qt source code.
This article will help you to understand the concepts.
</p>
</div>
<p>
In order to better understand this article, you need to know some basics of lock-free
programming. If you understand what the ABA problem is and know how to make a lock-free
stack, you are probably fine. Otherwise I recommend reading
<a href="http://woboq.com/blog/introduction-to-lockfree-programming.html">my previous post</a>
as an introduction.
</p>
<p>
The contents of this blog entry are taken from the last part of
<a href="http://qt-project.org/videos/watch/development-of-multi-threaded-applications">my presentation at
the Qt Developer days 2011</a>.
</p>
<h2>QMutex</h2>
<p>
Before understanding how something works, one needs to understand what it does first.
Here is the basic interface we are going to analyze.
</p>
<pre class="brush: cpp">
class QMutex {
public:
    void lock();
    void unlock();
    bool tryLock();
private:
    //...
};
</pre>
<p>
What it does is unsurprising.
If you don't guess what those functions do, you can read it in the
<a href="http://qt-project.org/doc/qt-4.8/qmutex.html">QMutex documentation</a>.
</p>
<h2>Motivation</h2>
<p>
We want QMutex to be as efficient as possible.
QMutex in Qt 4.8 is already quite fast because it is already using atomic operations.
So don't expect differences in speed between Qt 4.8 and Qt 5.
But what we improved is more from a memory perspective. We want QMutex to use as
little memory as possible, so you can put more QMutex in your objects to have more lock
granularity.
</p>
<pre class="brush: cpp">
sizeof(QMutex) == sizeof(void*).
</pre>
<p>
That condition was already true in Qt 4. But Qt 4 has lots of hidden costs because it is using
<a href="http://www.qtcentre.org/wiki/index.php?title=Private_implementation">pimpl</a>,
as almost every class in Qt does.
Constructing a QMutex in Qt 4 allocates and initializes a QMutexPrivate which itself initializes
some platform specific primitives. So we have a memory overhead of over 120 bytes per mutex and also
the cost of initialization/destruction.
In Qt 5, there are no more hidden costs per mutex.
</p>
<p>
Another good point is that it is now a <a href="http://en.wikipedia.org/wiki/Plain_old_data_structure">POD</a>.
This is good because QMutex is often used to lock global resources.
Then a global mutex seems the obvious thing to use.
But, in Qt, we want to avoid the use of global objects. Indeed, 
<a href="http://neugierig.org/software/chromium/notes/2011/08/static-initializers.html">global objects should 
be avoided</a>
especially in library code, because the order of initialization is unspecified and they slow down
the start-up even if that part of the library is not used.
But as PODs do not need to be initialized, they can be used as global object.
</p>
<pre class="brush: cpp">
QMutex singletonMutex; // static global object !!!  (OK only for POD)
MySingleton *MySingleton::self() {
    QMutexLocker locker(&amp;singletonMutex)
    if(!m_self)
        m_self = new MySingleton;
    return m_self;
}
</pre>
<p>
That code is dangerous in Qt 4 because maybe another global object in another compilation
unit wants to make use of the singleton and the mutex could be used before it is created.
</p>
<h3>Summary of the QMutex changes from Qt 4.8 to Qt 5</h3>
<ul>
    <li>QMutex uses much less memory.</li>
    <li>The construction and destruction is faster.</li>
    <li>It is now suitable as a global object.</li>
    <li>The cost of locking or unlocking should not have changed.</li>
</ul>
<h2>Overview</h2>
<pre class="brush: cpp">
class QMutex {
public:
    // API ...
private:
    QAtomicPointer&lt;QMutexPrivate&gt; d_ptr;
};
</pre>
<p>
    <code>d_ptr</code> is the only data member. The trick is that it is not always a pointer to an actual QMutexPrivate
It may have a magic value:</p>
<table border="1">
    <tr>
        <th> Value of <code>d_ptr</code>
        </th>
        <th>Meaning</th>
    </tr>
    <tr>
        <td>
            <code>0x0</code>
        </td>
        <td>The mutex is unlocked</td>
    </tr>
    <tr>
        <td>
            <code>0x1</code>
        </td>
        <td> The mutex is locked and no other threads are waiting</td>
    </tr>
    <tr>
        <td>Other address</td>
        <td>An actual pointer to a QMutexPrivate</td>
    </tr>
</table>
<p>
You should be familiar with a pointer having 0 (or <code>0x0</code>) as a value
(also called <code>NULL</code>).
<code>0x1</code> is a special value that represents an uncontended locked mutex.
</p>
<p>
So the principle of a lock is to try to atomically change the value of <code>d_ptr</code> from 0 to 1
If this succeeds, we have the lock, else, we need to wait.
</p>
<pre class="brush: cpp">
bool QMutex::tryLock() {
    return d_ptr.testAndSetAcquire(0x0, 0x1);
}

void QMutex::lock() {
    while(!d_ptr.testAndSetAcquire(0x0, 0x1)) {
        // change the value of d_ptr to a QMutexPrivate and call wait on it.
        // ... see bellow
    }
}
</pre>
<p>
The function <code>bool QAtomicPointer::testAndSetAcquire(expected, newValue)</code> will change the value
of the pointer to newValue only if the previous value is expected and returns true if it succeeds.
It does it atomically: If other threads change the value behind its back, the operation
would fail and returns false.
</p>
<h2> Unlock </h2>
<p>
Let us start with the code:
</p>
<pre class="brush: cpp">
void QMutex::unlock() {
    Q_ASSERT(d_ptr); // cannot be 0x0 because the mutex is locked.

    QMutexPrivate *d = d_ptr.fetchAndStoreRelease(0x0);
    if (d == 0x1)
        return; // no threads are waiting for the lock

    d-&gt;wake(); // wake up all threads
    d-&gt;deref();
}
</pre>
<p>
The function <code>fetchAndStoreRelease</code> will atomically exchange the value of
<code>d_ptr</code> to <code>0x0</code> and
return the previous value.  This exchange is atomic: it is guaranteed that we have the old value
and that no threads had put a different value in between.
</p>
<p>
The returned value cannot be 0, because our mutex was locked
(we have the lock, since we are unlocking it).
If it was <code>0x1</code>, no threads were waiting: we are finished.
Otherwise, we have a pointer to QMutexPrivate and threads are waiting, so we need to wake all
those threads up. They will then shortly try to lock the mutex again.
Waking all the threads while only one can acquire the mutex is a waste of CPU.
The real code inside Qt only wakes up one thread.
</p>
<p>
You will also notice a <code>deref()</code>. This will de-reference the <code>QMutexPrivate</code>
and release it if needed.
</p>
<h2>Memory Management</h2>
<p>
In lock free programming, memory management is always a difficult topic.
We use the technique of reference counting in order to make sure the
<code>QMutexPrivate</code> is not released while one thread is trying to use it.</p>
<p>It is important to see that the <code>QMutexPrivate</code> can never be deleted.
Consider this code:  
</p>
<pre class="brush: cpp">
d_ptr-&gt;ref().
</pre>
<p>
This is not an atomic operation.  The <code>ref()</code> itself is atomic, but there
is a step before.
The code first reads the value of <code>d_ptr</code> and puts the memory address in a register.
But another thread may unlock the mutex and release the <code>QMutexPrivate</code>
before the call to <code>ref()</code>.
We would end up accessing free'ed memory.
</p>
<p>
    <code>QMutexPrivate</code> are never deleted. Instead, they are put in a pool to be reused
(a lock-free stack).
We expect the total number of <code>QMutexPrivate</code> to be rather small.
A <code>QMutexPrivate</code> is only needed if there is a thread waiting,
and there cannot be more threads waiting than the number of threads on the application.
</p>
<p>
Here is how the <code>QMutexPrivate</code> looks
</p>
<pre class="brush: cpp">
class QMutexPrivate {
    QAtomicInt refCount;
public:
    bool ref() {
        do {
            int c = refCount;
            if (c == 0)       // do not reference a QMutexPrivate that
                return false; //   has been already released.
        } while (!refCount.testAndSetAcquire(c, c + 1))
        return true;
    }
    void deref() {
        if (!refCount.deref())
            release();
    }

    /* Release this QMutexPrivate by pushing it on the
       global lock-free stack */
    void release();

    /* Pop a mutex private from the global lock-free stack
       (or allocate a new one if the stack was empty)
       And make sure it is properly initialized
       The refCount is initially 1
      */
    static QMutexPrivate *allocate();

    /* Block until wake is called.
       If wake was already called, returns immediately */
    void wait();

    /* Wake all the other waiting threads. All further calls to wait()
       will return immediately */
    void wake();

    // ... platform specifics
};
</pre>
<h2>Lock</h2>
<p>
Now, we have got enough information to look at the implementation of the locking.
</p>
<pre class="brush: cpp">
void QMutex::lock() {
    // Try to atomically change d_ptr from 0 to 1
    while (!d_ptr.testAndSetAcquire(0x0, 0x1)) {
        // If it did not succeed, we did not acquire the lock
        // so we need to wait.

        // We make a local copy of d_ptr to operate on a
        // pointer that does not change behind our back.
        QMutexPrivate *copy = d_ptr;

        // It is possible that d_ptr was changed to 0 before we did the copy.
        if (!copy)     // In that case, the mutex is unlocked,
            continue;  // so we can try to lock it again

        if (copy == 0x1) {
            // There is no QMutexPrivate yet, we need to allocate one
            copy = QMutexPrivate::allocate();
            if (!d_ptr.testAndSetOrdered(0x1, copy)) {
                // d_ptr was not 0x1 anymore, either the mutex was unlocked
                // or another thread has put a QMutexPrivate.
                // either way, release the now useless allocated QMutexPrivate,
                // and try again.
                copy-&gt;deref();
                continue;
            }
        }

        // Try to reference the QMutexPrivate
        if (!copy-&gt;ref())  // but if it fails because it was already released,
            continue;      // the mutex has been unlocked, so try again

        // Now, it is possible that the QMutexPrivate had been released,
        // but re-used again in another mutex. Hence, we need to check that
        // we are really holding a reference to the right mutex.
        if (d_ptr != copy) {
            copy-&gt;deref();
            continue;
        }

        // From this point we know that we have the right QMutexPrivate and that
        // it won't be released or change behind our back.
        // So we can wait.
        copy-&gt;wait();

        // The mutex has been unlocked, we can release the QMutexPrivate
        copy-&gt;deref();
        // and retry to lock.
    }
}
</pre>
<p>I hope that the comments were self explanatory.</p>
<h2>To The Real Code.</h2>
<p>
The simplified algorithms code shown here has some limitations that have been solved in the real implementation inside Qt:
</p>
<ul>
    <li> QMutex has a recursive mode with the same API (the Qt 5 implementation supports them but they
   are more expensive than non-recursive mutex) </li>
    <li> This simplification wakes all the threads waiting on a single mutex instead of just one.
     That is not optimal since only one is going to acquire the lock.</li>
    <li> It is not fair. This means that a thread waiting for a long time might never acquire the mutex while
   two other threads always exchange the mutex between each other.</li>
    <li> There is the <code>QMutex::tryLock(int timeout)</code> that only blocks for a limited amount of time
  if the mutex cannot be acquired.</li>
</ul>
<p>
This code is also not used on Linux. On Linux, we use the <a href="http://en.wikipedia.org/wiki/Futex">futexes</a>, using
the <code>d_ptr</code> as the futex controller.
</p>
<p>
If you are interested, you can look at the actual code: the file qmutex.cpp, qmutex.h and qmutex_p.h available on
<a href="http://qt.gitorious.org/qt/qtbase/trees/master/src/corelib/thread">Gitorious</a>
</p>
]]></description></item>
<item><title>Introduction to Lock-free Programming with C++ and Qt</title><link>http://woboq.com/blog/introduction-to-lockfree-programming.html</link><pubDate>Tue, 13 Dec 2011 14:14:29 GMT</pubDate><description><![CDATA[<div class="intro">
    <p>
This blog post is an introduction to lock-free programming.
I'm writing this because this is the pre-requisite to understand 
<a href="http://woboq.com/blog/internals-of-qmutex-in-qt5.html">my next post</a>.
This was also the content of my presentation for 
<a href="http://woboq.com/blog/qt-devdays-2011.html">Qt Developer Days 2011</a>.</p>
    <p>
        <a href="http://en.wikipedia.org/wiki/Non-blocking_algorithm">Lock-free programming</a>
is the design of algorithms and data structures that do not
acquire locks or mutexes.</p>
</div>
<p>
When different threads in your program need to access
the same data, we must ensure that the data is always in a coherent state when 
used. One way to achieve that is to do locking. A thread will 
acquire a mutex to write the data. That thread may touch the data structure and
have it in an inconsistent state as it holds the mutex, but this is not a problem 
because other threads 
cannot access the data at this time as they will block waiting for the mutex 
to be released.
While a thread is waiting, the OS will schedule another thread or process or
let the CPU core rest.</p>
<h2>What is wrong with Mutexes?</h2>
<p>Mutexes are perfectly fine. But you have a problem if there is lock contention.
If you want your algorithm to be fast, you want to use the available cores
as much as possible instead of letting them sleep.
A thread can hold a mutex and be de-scheduled by the CPU (because of a cache miss
or its time slice is over). Then all the threads that want to acquire this 
mutex will be blocked.
And if you have a lot of blocking, the OS also needs to do more context
switches which are expensive because they clear the caches.</p>
<p>Other problems may arise if you do real time programming
(<a href="http://en.wikipedia.org/wiki/Priority_inversion">priority inversion</a>, 
 <a href="http://en.wikipedia.org/wiki/Lock_convoy">convoying</a>, ...).
Mutexes also cannot be used in signal handlers.
</p>
<p>Another example: Let us suppose you want to split your program into different processes
so the whole application does not crash if one process crashes. 
(This is what modern browsers
are doing by having the rendering of the page in a different process.)
But if the process crashes while holding a shared lock you are in big trouble
as this will most likely cause a dead lock in the main application.</p>
<h3>So how can we do it without locking?</h3>
<p>Modern CPUs have something called <a href="http://en.wikipedia.org/wiki/Atomic_operation">
atomic operations</a>. There are libraries that
have APIs that let you use those atomic operations.
Qt has two classes: QAtomicInt and QAtomicPointer.
Other libraries or languages might have different primitives, but the principles
are the same.</p>
<h2>QAtomic API</h2>
<p>I won't go into the detail of the API here as you can read the documentation
of <a href="http://qt-project.org/doc/qt-4.8/qatomicint.html">QAtomicInt</a> and 
<a href="http://qt-project.org/doc/qt-4.8/qatomicpointer.html">QAtomicPointer</a>
</p>
<p>But here are the highlights: Both classes have a similar API.
They wrap an <tt>int</tt> or a pointer and allow to make atomic operations on it.
There are 3 main operations: <tt> fetchAndAdd, fetchAndStore</tt>, and <tt>testAndSet</tt>.
They are available in 4 variants, one for each ordering.
</p>
<p>The one used here is <tt>testAndSet</tt>. 
It is also called <a href="http://en.wikipedia.org/wiki/Compare-and-swap">Compare and Swap</a> 
in the literature.<br/>
Here is a non-atomic implementation</p>
<pre class="brush: cpp">
bool QAtomicInt::testAndSet(int expectedValue, int newValue) {
    if (m_value != expectedValue)
        return false;
    m_value = newValue;
    return true;
}
</pre>
<p>What it does: it changes the wrapped value only if the value is the expected value, else
it does not touch it and returns false.</p>
<p>It is atomic, meaning that if two threads operate at the value on the same time it stays consistent.</p>
<p>Of course, it is not implemented like this as it would not be atomic.
It is implemented using assembly instructions. 
Qt's atomic classes are one of the very few places inside Qt implemented with assembly on each platform.</p>
<h2>Memory Ordering</h2>
<p>Today's CPUs have what is called 
<a href="http://en.wikipedia.org/wiki/Out-of-order_execution">out of order execution</a>.
What it means is that at each clock cycle, the CPU might read several instructions (say 6)
from the memory and decode them and store them in a pool of instructions.
The wires in the CPU will compute the dependencies between the instructions
and feed the processing units with the instructions in the best possible order
making the most efficient use of the CPU. So the instructions, and especially 
the reads and the store, are executed in an order that might be different from the
one in the original program.
The CPU is allowed to do that as long as it gives the same result on that thread.</p>
<p>However, we want to make sure that the ordering is preserved when we play
with atomic operations. Indeed, if the memory is written in a different
order, the data structure may be in an inconsistent state when other threads
read the memory.</p>
<p>Here is an example:</p>
<pre class="brush: cpp">
  QAtomicPointer&lt;int&gt; p;
  int x;
  //...
  x = 4;
  p.fetchAndStoreRelease(&amp;x);
</pre>
<p>It is important that when <tt>p</tt> is set to <tt>&amp;x</tt>, the value of <tt>x</tt> is already 4.
Else another thread could see the value of p that is still pointing to 
something else.</p>
<p>This is done by adding the proper memory fence in the program. Memory fences
are special instructions that tell the CPU to not reorder. We have 4 kind of
fences:</p>
<dl>
    <dt>
        <b>Acquire</b>
    </dt>
    <dd> No reads or writes that happen after will be moved before the 
            atomic operations.</dd>
    <dt>
        <b>Release</b>
    </dt>
    <dd>The opposite of Acquire: No reads or writes are going to be moved 
            after.</dd>
    <dt>
        <b>Ordered</b>
    </dt>
    <dd>It is a mix of the two previous orderings: Nothing can be moved after
            or before. This is the safest and the one to use if you don't know which one to use.</dd>
    <dt>
        <b>Relaxed</b>
    </dt>
    <dd>No memory fences are added.</dd>
</dl>
<p>
The fence hints are added to the functions because on some architectures,
there is one assembly instruction to do the atomic operation and the fence.
</p>
<p>
The fences are only there for keeping the CPU away from reordering. It has nothing to do
with the fact that the compiler might also re-order everything. We make sure
the compiler does not re-order by having '<tt>volatile</tt>' access.
</p>
<h2>Lock-free Stack</h2>
<p>We will here design a stack that works without locking:</p>
<pre class="brush: cpp">
class Stack {
    QAtomicPointer&lt;Node&gt; head;
public:
    Stack() : head(0) {}
    void push(Node *n) {
        do {
            n-&gt;next = head;
        } while(!head.testAndSetOrdered(n-&gt;next, n));
    }
    Node *pop() {
        Node *n;
        do {
            n = head;
            if (!n)
                return 0;
        } while(!head.testAndSetOrdered(n, n-&gt;next));
        return n;
    }
};
</pre>
<p>I'll use drawings to show how the code works:</p>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/stack1.png" alt="A Stack"/>
<p>It is basically implemented as a 
<a href="http://en.wikipedia.org/wiki/Linked_list">linked list</a>:
each node has a pointer to the next node,
and we have a pointer to the first node called head.</p>
<h3>Push</h3>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/stack2.png" alt="Push 1"/>
<p>In this example, two threads want to push a node to the stack. 
Both threads have already executed the line <code>n-&gt;next = head</code> and will soon execute 
the atomic operation that will change <tt>head</tt> from the former head (<tt>B</tt>)
to <tt>n</tt> (<tt>C</tt> or <tt>D</tt>)</p>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/stack3.png" alt="Push 2"/>
<p>In this image we see that the Thread 2 was first. And <tt>D</tt> is now on the stack.</p>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/stack4.png" alt="Push 3"/>
<p>The <tt>testAndSet</tt> in Thread 1 will fail. The <tt>head</tt> is not <tt>B</tt> anymore.
<tt>head</tt> is not changed, meaning that the node <tt>D</tt> is still on the stack.</p>
<p>The Thread 1 will be notified that the testAndSet has failed and will then retry with 
the new <tt>head</tt> which is now <tt>D</tt>
</p>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/stack5.png" alt="Push 4"/>
<h2>Benchmark</h2>
<p>So you can try yourself with this little example: 
<a href="introduction-to-lockfree-programming/lockfreestack.cpp">lockfreestack.cpp</a>
    <br/>
(Download the file in a new directory and do <code>qmake -project &amp;&amp; qmake &amp;&amp; make</code>)
</p>
<p>This program first pushes 2 million nodes to the list using 4 threads, measuring the time 
it takes.  Once all the threads have finished pushing, it will pop all those nodes using 4 threads
and measure how long that takes</p>
<p>The program contains a version of the stack that uses QMutex (in the <code>#if 0</code> block)</p>
<p>Results: (on my 4 core machine)</p>
<table border="1">
    <tr>
        <th/>
        <th>Push (ms)</th>
        <th>Pop (ms)</th>
        <th>Total (real / user / sys) (ms)</th>
    </tr>
    <tr>
        <th>With QMutex</th>
        <td>3592</td>
        <td>3570</td>
        <td>7287 / 4180 / 11649</td>
    </tr>
    <tr>
        <th>Lock-free</th>
        <td>185</td>
        <td>237</td>
        <td>420 / 547 / 297</td>
    </tr>
</table>
<p>Not bad: the lock-free stack is more than 100 times faster. As you can see, there is much 
less contention (the <em>real</em> is smaller than the <em>user</em>) in the lock-free case, while
with the mutex, a lot of time is spent blocking.</p>
<h2>The ABA problem</h2>
<p>OK, there is actually a big bug in our implementation. It works well in the benchmark
because we push all the node then pop them all. There is no thread that pushes an pops nodes
at the same time. In a real application, we might want to have a stack that works 
even if threads are pushing and popping nodes at the same time.</p>
<p>But what is the problem exactly?  Again, I'll use some images to show:</p>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/aba1.png" alt="ABA Problem 1"/>
<p>In this example, the Thread 1 wants to pop a node.
It take the address of <tt>A</tt> and will do a <tt>testAndSet</tt>
to change <tt>head</tt> atomically from <tt>A</tt> to <tt>B</tt>.
But it is de-scheduled by the OS just before the atomic operation while another thread 
is being executed</p>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/aba2.png" alt="ABA Problem 2"/>
<p>While Thread 1 is sleeping, Thread 2 also pops a node, so <tt>A</tt> is not on the stack anymore.</p>
<p>If Thread 1 wakes up now, the atomic operation in Thread 1 will fail because <tt>head</tt> is not anymore 
equal to <tt>A</tt>.  But Thread 1 does not wake up and Thread 2 continues...</p>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/aba3.png" alt="ABA Problem 3"/>
<p>Thread 2 has pushed a node (<tt>C</tt>).  Again, if thread 1 would wake up now, there would not
be any problem, but it still does not wake up.</p>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/aba4.png" alt="ABA Problem 4"/>
<p>And Thread 2 pushes <tt>A</tt> back in the stack</p>
<img src="http://woboq.com/blog/introduction-to-lockfree-programming/aba5.png" alt="ABA Problem 5"/>
<p>But now, Thread 1 wakes up and execute the testAndSet, which succeeds as <tt>head</tt> is
<tt>A</tt> again.  This is a problem because now <tt>C</tt> is leaking.</p>
<p>It could have been even worse if Thread 2 had popped the node <tt>B</tt>.</p>
<h3>Solutions to the ABA Problem</h3>
<p>Every problem has solutions.
It is outside the scope of this article to show the solutions in details. I would just
give some hint that will orient your research on the web:</p>
<ul>
    <li>Adding a serial number to the pointer, incremented each time a node is popped.
It can be stored inside the least significant bits of the pointer (considering it points to an aligned address). 
But that might not be enough bits. Instead of using pointers, one can use indexes in array, 
leaving more bits for the serial number.</li>
    <li>
        <a href="http://en.wikipedia.org/wiki/Hazard_pointer">Hazard pointer</a>: Each thread puts the pointer
it reads in a list readable by all threads. Those lists are then checked before reusing a node.</li>
    <li>Double or multiple word compare and swap. (which is possible using single word compare and swap)</li>
</ul>
<h2>Conclusions</h2>
<p>
As you might see, developing lock-free algorithm requires much more 
thinking than writing blocking algorithms. So keep mutexes, unless you have
a lot of lock contention or are looking for a challenge.
</p>
<p>
A question I often got is whether it is not better to lock in order to let the other threads working
instead of entering what might appear to be a spin lock.
But the reality is that it is not a spin lock. The atomic operations succeed much more
often than they fail. And they only fail if there was progress (that is, another thread made progress).
</p>
<p>
If you need help in your Qt applications regarding threads and locking, maybe
<a href="http://woboq.com/">Woboq can help you</a>.
</p>
]]></description></item>
</channel></rss>