<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>{(something&#124;&#124;other).soft()} &#187; c++</title>
	<atom:link href="http://www.somethingorothersoft.com/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.somethingorothersoft.com</link>
	<description>About Software Development And Other Stuff By Igor Zevaka</description>
	<lastBuildDate>Fri, 18 Jun 2010 00:15:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>A few things you might not know about System.Nullable</title>
		<link>http://www.somethingorothersoft.com/2010/05/29/a-few-things-you-might-not-know-about-system-nullable/</link>
		<comments>http://www.somethingorothersoft.com/2010/05/29/a-few-things-you-might-not-know-about-system-nullable/#comments</comments>
		<pubDate>Sat, 29 May 2010 13:59:24 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=385</guid>
		<description><![CDATA[There is plenty of information about Nullable&#60;T&#62; type out there and how to use it. There are, however a few tidbits that are not quite as obvious at first glance. Nullable is a value type It&#8217;s a struct that can be null. The only reason why int? intVal = null; compiles is because C# compiler <a href="http://www.somethingorothersoft.com/2010/05/29/a-few-things-you-might-not-know-about-system-nullable/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>There is plenty of information about <code>Nullable&lt;T&gt;</code> type out there and how to use it. There are, however a few tidbits that are not quite as obvious at first glance.</p>

<h1>Nullable<T> is a value type</h1>

<p>It&#8217;s a struct that can be null. The only reason why <code>int? intVal = null;</code> compiles is because C# compiler supports nullable types. You <strong>cannot</strong> define the same kind of struct yourself.</p>

<p>The decision to make <code>Nullable&lt;T&gt;</code> a value type actually makes sense if you think about it. Calling its member methods and properties will always succeed, i.e. NullReferenceException will never be thrown. This gurantees that <code>HasValue</code> never throws a NullReferenceException.</p>

<h1>Comparison to null</h1>

<p>Under the hood, the compiler, in fact translates comparison to null to a call to HasValue. The below MSIL demonstrates that:</p>

<div>
<pre class="brush: csharp;">
    .locals init ([0] valuetype [mscorlib]System.Nullable`1&lt;int32&gt; 'value',
           [1] bool hasvalue,
           [2] bool hasvalue2)

    //int? value = null;
    IL_0001:  ldloca.s   'value'
    IL_0003:  initobj    valuetype [mscorlib]System.Nullable`1&lt;int32&gt;
    //bool hasvalue = value.HasValue;
    IL_0009:  ldloca.s   'value'
    IL_000b:  call       instance bool valuetype [mscorlib]System.Nullable`1&lt;int32&gt;::get_HasValue()
    IL_0010:  stloc.1
    //bool hasvalue2 = value != null;
    IL_0011:  ldloca.s   'value' //loads a variable onto evaluation stack
    IL_0013:  call       instance bool valuetype [mscorlib]System.Nullable`1&lt;int32&gt;::get_HasValue() //calls HasValue
    IL_001b:  stloc.2 //Stores the result in location 2 (hasvalue2)
</pre>
</div>

<p>As you can see the generated IL for <code>hasvalue = value.HasValue</code> and <code>hasvalue2 = value != null</code> are identical.</p>

<h1>null Assignment</h1>

<p>Also from above code you can see that assigning null to a nullable value is the same as calling the parameterless contructor (which all value types have).</p>

<h1>Ternary operator</h1>

<p>C# compiler also does special things with ternary operator for nullable types. The following code compiles:</p>

<div>
<pre class="brush: csharp;">
int? nullableIntVal = 4;
int intVal = nullableIntVal ?? -1;
</pre>
</div>

<p>The above is just syntactic sugar for calling <code>HasValue</code> and if it&#8217;s true calling GetValueOrDefault(). The compiler actually generates a temporary variable to call <code>HasValue</code> off in both Release and Debug modes. Not sure why that is. Below code illustrates the equivalent C# code to what the compiler generates for ternary operator.</p>

<div>
<pre class="brush: csharp;">
int? nullableIntVal = 4;
int? temp = nullableIntVal;
int intVal = temp.HasValue ?? temp.GetValueOrDefault() : -1;
</pre>
</div>

<h1>Summary</h1>

<p><code>Nullable&lt;T&gt;</code> is a special value type that has support from C# compiler to allow the following:</p>

<ul>
<li><code>null</code> assignment  &#8211; under the hood: calling defualt constructor.</li>
<li><code>null</code> comparison &#8211; under the hood: calling <code>HasValue</code> property.</li>
<li>ternary operator <code>??</code> &#8211; under the hood: calling <code>HasValue</code> and conditionally <code>GetValueOrDefault</code>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/05/29/a-few-things-you-might-not-know-about-system-nullable/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Double Dispatch &#8211; RTTI vs. Pure Vtable</title>
		<link>http://www.somethingorothersoft.com/2010/02/02/double-dispatch-rtti-vs-pure-vtable/</link>
		<comments>http://www.somethingorothersoft.com/2010/02/02/double-dispatch-rtti-vs-pure-vtable/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 22:16:03 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=235</guid>
		<description><![CDATA[As Jeremy Clarkson would say, I have been inundated with a request to performance test a dynamic_cast DD mechanism against the pure vtable one. The results surprised me, both in Debug and Release modes. So here is the dynamic_cast implementation: void c_rtti::foobar(a_rtti &#38; a2) { c_rtti* c_ = dynamic_cast&#60;c_rtti*&#62;(&#38;a2); if (c_) { ::foobar(*this,*c_); return; } <a href="http://www.somethingorothersoft.com/2010/02/02/double-dispatch-rtti-vs-pure-vtable/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>As Jeremy Clarkson would say, I have been inundated with <a href="http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/comment-page-1/#comment-250">a request</a> to performance test a <code>dynamic_cast</code> DD mechanism against the <a href="http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/">pure vtable</a> one. The results surprised me, both in Debug and Release modes. So here is the <code>dynamic_cast</code> implementation:</p>

<div class="foo">
<pre class="brush: cpp;">
void c_rtti::foobar(a_rtti &amp; a2) {
   c_rtti* c_ = dynamic_cast&lt;c_rtti*&gt;(&amp;a2);
   if (c_) {
      ::foobar(*this,*c_);
      return;
   }
   b_rtti* b_ = dynamic_cast&lt;b_rtti*&gt;(&amp;a2);
   if (b_) {
      ::foobar(*b_, *this);
   }
}
</pre>
</div>

<p>I have used the most non-trivial case where the above function is called with <code>a2</code> parameter pointing to an instance of <code>b_rtti</code>, thus triggerring two dynamic casts. I used the same technique on the vtable implementation for consistency, although it doesn&#8217;t matter as the sequence of execution is the same for any combination of objects. The test ran for 4 million iterations.</p>

<p>Here is the test code:</p>

<div class="foo">
<pre class="brush: cpp;">
        a&amp; a_ = c();
        b bInstance;
        a&amp; b_ = bInstance;
        a_.foobar(b_);
</pre>
</div>

<p>Just to show what actually happens in both implementations, here are the sequence diagrams.</p>

<h4>vtable:</h4>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/vtable1.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/vtable1.png" alt="" title="vtable" width="346" height="230" class="alignnone size-full wp-image-238" /></a></p>

<h4>dynamic_cast:</h4>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/rtti.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/rtti.png" alt="" title="dynamic_cast Sequnce Diagram" width="254" height="304" class="alignnone size-full wp-image-236" /></a></p>

<h3>The results</h3>

<p>In debug mode, RTTI implementation is about 20% faster:</p>

<pre><code>No RTTI - 1685 milleseconds.
With RTTI - 1295 milleseconds.(23.15% faster)
</code></pre>

<p>So this is pretty insignificant in a real life application and I doubt it would come in the profiler. By my calculation there is about 100 clock cycles (on a 1Ghz CPU) difference between the two per call.</p>

<p>In Release mode things get interesting:</p>

<pre><code>No RTTI - 62 milleseconds.
With RTTI - 780 milleseconds.(-1158.06% faster)
</code></pre>

<p>The pure vtable version is ten times faster!!! Of course this again means very little in the real world. It&#8217;s worth noting that the RTTI verson is twice faster in Release mode. What is also interesting is that in Debug mode vtable is slower by 100 clock cycles, in release it&#8217;s faster by 200.</p>

<p>To summarise. The real life value of this performance analysis is zero. If you are Google and you had 100 PhDs design the program and another 100 wrote the library routines for it, doing this optimization will improve the performance by about 0.000001%. In any other case, this is textbook case of premature optimisation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/02/02/double-dispatch-rtti-vs-pure-vtable/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Double dispatch without RTTI</title>
		<link>http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/</link>
		<comments>http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 22:15:16 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=230</guid>
		<description><![CDATA[I liked my StackOverflow answer so much that I decided to make it into a blog post. The question was how to implement a double dispatch mechanism for subclasses of one base class without casting. After dismissing the question as stupid, I spent a bit of time trying to come up with a solution that <a href="http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I liked my <a href="http://stackoverflow.com/questions/2159496/c-problem-with-function-overloading/2159524#2159524">StackOverflow answer</a> so much that I decided to make it into a blog post. The question was how to implement a double dispatch mechanism for subclasses of one base class without casting. After dismissing the question as stupid, I spent a bit of time trying to come up with a solution that didn&#8217;t rely on <code>dynamic_cast</code>. The solution is pretty pointless as it&#8217;s pretty confusing and might be slower than RTTI solution due to an extra function call. It was largely inspired by wikipedia article on double dispatch found <a href="http://en.wikipedia.org/wiki/Double_dispatch">here</a>.</p>

<p>So the trick to get this working as pointed out in the article was to call the function on the pointer or reference of the parameter to the original function, thus cauising a second dispatch.</p>

<div class="foo">
<pre class="brush: cpp;">
class A {
  virtual void PublicFunction(B&amp; b) {
    b.PerformFunction(*this);
  }
}
</pre>
</div>

<p>The problem with doing this sort of thing with subclasses of the same base is that we need to allow the possibility of the base class being called with one of its subclasses as a parameter. Luckily we can use forward declarations to define the functions and implement them later on.</p>

<div class="foo">
<pre class="brush: cpp;">
class b;
class c;
class a {
protected:
    virtual void doFoobar(a&amp; a2); //do stuff here 
    virtual void doFoobar(b&amp; b2); //delegate to b
    virtual void doFoobar(c&amp; c2); //delegate to c
public:
    virtual void foobar(a&amp; a2) {
        a2.doFoobar(*this);
    }
    friend class b;
    friend class c;
};
class b : public a {
protected:
    virtual void doFoobar(a&amp; a2); //do stuff here 
    virtual void doFoobar(b&amp; b2); //do stuff here
    virtual void doFoobar(c&amp; c2); //delegate to c
public:
    virtual void foobar(a&amp; a2) {
        a2.doFoobar(*this);
    }
    friend class a;
};
class c : public b {
protected:
    virtual void doFoobar(a&amp; a2); //do stuff here 
    virtual void doFoobar(b&amp; b2); //do stuff here
    virtual void doFoobar(c&amp; c2); //delegate to c
public:
    virtual void foobar(a&amp; a2) {
        a2.doFoobar(*this);
    }
    friend class a;
    friend class b;
};
//class a
void a::doFoobar(a&amp; a2)  {
    printf(&quot;Doing a&lt;-&gt;a\n&quot;);
}
void a::doFoobar(b&amp; b2)  {
    b2.doFoobar(*this);
}
void a::doFoobar(c&amp; c2)  {
    c2.doFoobar(*this);
}
//class b
void b::doFoobar(a&amp; a2)  {
    printf(&quot;Doing b&lt;-&gt;a\n&quot;);
}
void b::doFoobar(b&amp; b2)  {
    printf(&quot;Doing b&lt;-&gt;b\n&quot;);
}
void b::doFoobar(c&amp; c2)  {
    c2.doFoobar(*this);
}
//class c
void c::doFoobar(a&amp; a2)  {
    printf(&quot;Doing c&lt;-&gt;a\n&quot;);
}
void c::doFoobar(b&amp; b2)  {
    printf(&quot;Doing c&lt;-&gt;b\n&quot;);
}
void c::doFoobar(c&amp; c2)  {
    printf(&quot;Doing c&lt;-&gt;c\n&quot;);
}
</pre>
</div>

<p>The code is far from an ideal double dispatch solution as it relies on the forward declaration trick to resolve the circular dependency between the subclasses. This means that all the classes that need to have this functionality must be known at compile-time (of the base class). This means the base class cannot be made into a library component.</p>

<p>To explain all the friend declarations. Considering the fact that all the classes <code>a</code>, <code>b</code> and <code>c</code> are tightly coupled as is, I added friend declarations so that the actual worker function is private and cannot be called from the outside.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Shouldn&#8217;t RAII should be RDID???</title>
		<link>http://www.somethingorothersoft.com/2009/12/11/shouldnt-raii-should-be-rdid/</link>
		<comments>http://www.somethingorothersoft.com/2009/12/11/shouldnt-raii-should-be-rdid/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 12:16:27 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[design-patterns]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=157</guid>
		<description><![CDATA[I will openly plead ignorance for design patterns. I know this is really not the way to be and Design Patterns and Code Complete are on my &#8220;to read&#8221; list. It&#8217;s only that I trawl through StackOverflow a bit lately that I get to hear a lot of buzz about patterns and idioms. Some people <a href="http://www.somethingorothersoft.com/2009/12/11/shouldnt-raii-should-be-rdid/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I will openly plead ignorance for design patterns. I know this is really not the way to be and <em>Design Patterns</em> and <em>Code Complete</em> are on my &#8220;to read&#8221; list. It&#8217;s only that I trawl through StackOverflow a bit lately that I get to hear a lot of buzz about patterns and idioms. Some people get really obsessive about identifying the patterns and making sure they use the right one. But that&#8217;s not really the point of this post.</p>

<p>Most of the time I realize that a lot of those pattens is osmething that I have been doing for years without thinking. In fact this inspires me to go through &#8220;the list&#8221; of all the patterns and do a series of blog posts &#8211; <strong>&#8220;Design Patterns &#8211; What you have coded for years is actually an idiom &#8211; [insert design pattern here]&#8220;</strong>.</p>

<p>So, I only just recently found out that the practice of using smart pointers is officially called RAII &#8211; Resource Allocation Is Initialization. The  <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">Wikipedia article</a> bangs on about ojects being allocated on the stack and exception safety, but in my opinion those considerations are not as significant as the magic of destruction.</p>

<p>The only way this works in C++ is due to deterministic destructors. The magic happens upon destruction, not upon initialization. Any garbage collected language can have Allocation on Initialization, but they can&#8217;t guarantee implicit destruction when going out of scope like C++ does.</p>

<p>I also think that that object scope (the fact that it should be on the stack) is somewhat peripheral again. The destructor will get called whenever you explicitly delete the object as well. Whilst this is not strictly automagic destruction, it can be &#8211; for example when using collections that are aware of element removal semantics. For example a collection might either call a Release method on a ref counted object or call operator delete on plain old pointer.</p>

<p>So this brings me back to the title of hte post &#8211; shouldn&#8217;t Resource Allocation Is Initialization be Resource Deallocation Is Destruction? That&#8217;s where the magic happens, right?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2009/12/11/shouldnt-raii-should-be-rdid/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
