<?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>Marius Bancila's Blog &#187; C++</title>
	<atom:link href="http://mariusbancila.ro/blog/category/it/software/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://mariusbancila.ro/blog</link>
	<description>Sharing my opinions and ideas!</description>
	<lastBuildDate>Sun, 08 Aug 2010 09:36:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Colors Game Redux</title>
		<link>http://mariusbancila.ro/blog/2010/08/06/colors-game-redux/</link>
		<comments>http://mariusbancila.ro/blog/2010/08/06/colors-game-redux/#comments</comments>
		<pubDate>Fri, 06 Aug 2010 09:50:36 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[pointers]]></category>
		<category><![CDATA[vector]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=655</guid>
		<description><![CDATA[Two days ago I posted a simple implementation of a game of colors. Though it was intended only as an exercise, someone has criticizes the use of an int** to hold the grid information, mainly for two reasons: the footprint on 64-bit platforms can get nasty the explicitly allocated memory, instead of using a std::vector [...]]]></description>
			<content:encoded><![CDATA[<p>Two days ago I <a href="http://mariusbancila.ro/blog/2010/08/04/colors-game/">posted</a> a simple implementation of a game of colors. Though it was intended only as an exercise, someone has criticizes the use of an <strong>int**</strong> to hold the grid information, mainly for two reasons:</p>
<ul>
<li>the footprint on 64-bit platforms can get nasty</li>
<li>the explicitly allocated memory, instead of using a std::vector</li>
</ul>
<p>So this is the code:</p>
<pre class="prettyprint">
int** m_pCells; 

void Create()
{
   m_pCells = new int*[m_nSize];
   for(int i = 0; i < m_nSize; ++i)
      m_pCells[i] = new int[m_nSize];
}
</pre>
<p>Let's see how much memory it takes. The total size should be:</p>
<pre class="prettyprint">
totalsize = sizeof(m_pCells) + sizeof(m_pCells[0]) * m_nSize + m_nSize * m_nSize * sizeof(int);
</pre>
<p>On 32-bit platforms, the size of a pointer is the same with the size of int and is 4 bytes. For the maximum size allowed for my grid, which is 50, the total size in bytes for the grid is: 4 + 4*50 + 50*50*4 = 10204.</p>
<p>On 64-bit platforms, the size of a pointer is 8 bytes, but the size of int is still 4 bytes. So for a grid with 50 rows and columns it needs: 8 + 8*50 + 50*50*4 = 10408 bytes. That's a 2% increase of required memory.</p>
<p>The memory footprint was the last thing I had in mind when I wrote this simple exercise. Well, of course there is a way to require only 4 more bytes on 64-bit platforms. And that is using an <strong>int*</strong> allocating m_nSize*m_nSize elements.</p>
<pre class="prettyprint">
int* m_pCells;

void Create()
{
   m_pCells = new int[m_nSize * m_nSize];
}

void Destroy()
{
   delete [] m_pCells;
   m_pCells = NULL;
}
</pre>
<p>With this implementation, when you need to access the element at row i and column j, you have to use <strong>m_pCells[i * m_nSize + j]</strong>.</p>
<p>As for the second argument, that explicitly using operator new[] to allocate memory instead of using a vector of vectors, well, what could I say? Sure, why not. Different people use different programming styles. As long as all implementation are correct and achieve the same goal with similar performance, I guess everyone is entitle to code as he/she wants. But if we go back to the memory footprint, I would also guess that the use of vectors would take more memory than pointers to int, because the size of a vector is several times the size of a pointer. But I wouldn't say that's an important issue here. </p>
<p>Anyway, these arguments remember me the joke (or maybe it's serious) about the rules of optimization:</p>
<ol>
<li>Don't optimize.</li>
<li>Don't optimize yet (for experts only).</li>
</ol>
<p>(Of course there are super experts that can ignore these rules.)</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/08/06/colors-game-redux/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Colors Game</title>
		<link>http://mariusbancila.ro/blog/2010/08/04/colors-game/</link>
		<comments>http://mariusbancila.ro/blog/2010/08/04/colors-game/#comments</comments>
		<pubDate>Wed, 04 Aug 2010 14:08:04 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[colors]]></category>
		<category><![CDATA[games]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=649</guid>
		<description><![CDATA[One of the games I like the most on my new phone is about covering a grid formed by cells of different colors with a single color within a limited number of moves. After playing it again and again for a week, I decided to write my own game for the PC. The rules are: [...]]]></description>
			<content:encoded><![CDATA[<p>One of the games I like the most on my new phone is about covering a grid formed by cells of different colors with a single color within a limited number of moves. After playing it again and again for a week, I decided to write my own game for the PC.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/08/colorsgame.png" title="Colors Game" class="alignnone" width="773" height="596" /></p>
<p>The rules are:</p>
<ul>
<li>the grid has an equal number of rows and columns, that can vary from 5 to 50</li>
<li>cells are colored with six colors</li>
<li>coloring the grid always starts from the top left cell</li>
<li>adjacent cells having the same color form a single shape; game ends when this shape covers the entire grid</li>
<li>to change the color of the growing shape, use the six buttons available on the right side of the grid</li>
<li>grid must be covered within a number of moves; if you exceed that number of moves you lose</li>
<li>when you win, you automatically get to the next level</li>
<li>you can change the size of the grid from the menu</li>
</ul>
<p>Here are the available downloads: <a href="http://www.mariusbancila.ro/blog/wp-content/uploads/2010/08/ColorsGame_src.zip">the sources</a>, and <a href="http://www.mariusbancila.ro/blog/wp-content/uploads/2010/08/ColorsGame_binary.zip">the executable</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/08/04/colors-game/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2010 changes for VC++ (summary)</title>
		<link>http://mariusbancila.ro/blog/2010/04/02/visual-studio-2010-changes-for-vc-summary/</link>
		<comments>http://mariusbancila.ro/blog/2010/04/02/visual-studio-2010-changes-for-vc-summary/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 12:05:42 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[MFC]]></category>
		<category><![CDATA[VC++ VS2010 C++ MFC]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=514</guid>
		<description><![CDATA[In the past months I have written about what&#8217;s new in Visual Studio 2010 with regard to Visual C++. In this post I will summarize these articles. MSBuild and multi-targeting Visual Studio 2010 changes for VC++ (part 1) IntelliSense and Browsing (#include auto completion, call hierarchy, red squiggles, find all references, class wizard) Visual Studio [...]]]></description>
			<content:encoded><![CDATA[<p>In the past months I have written about what&#8217;s new in Visual Studio 2010 with regard to Visual C++. In this post I will summarize these articles.</p>
<ul>
<li>MSBuild and multi-targeting<br />
<a href="http://mariusbancila.ro/blog/2010/03/17/visual-studio-2010-changes-for-vc-part-1/">Visual Studio 2010 changes for VC++ (part 1)</a>
</li>
<li>IntelliSense and Browsing (#include auto completion, call hierarchy, red squiggles, find all references, class wizard)<br /> <a href="http://mariusbancila.ro/blog/2010/03/18/visual-studio-2010-changes-for-vc-part-2/">Visual Studio 2010 Changes for VC++ (part 2)</a></li>
<li>C++ compiler changes (static_assert, auto keyword, lambda, decltype, rvalue references)<br />
<a href="http://mariusbancila.ro/blog/2010/03/22/visual-studio-2010-changes-for-vc-part-3/">Visual Studio 2010 changes for VC++ (part 3)</a><br />
<a href="http://mariusbancila.ro/blog/2009/02/25/c-static_assert-a-niche-feature/">C++ static_assert, a niche feature</a><br />
<a href="http://mariusbancila.ro/blog/2009/02/24/lambdas-in-c/">Lambdas in C++</a><br />
<a href="http://mariusbancila.ro/blog/2009/02/22/type-inference-in-c/">Type inference in C++</a>
</li>
<li>Ribbon designer<br /> <a href="http://mariusbancila.ro/blog/2010/03/23/visual-studio-2010-changes-for-vc-part-4/">Visual Studio 2010 changes for VC++ (part 4)</a></li>
<li>Deployment changes<br /> <a href="http://mariusbancila.ro/blog/2010/03/24/visual-studio-2010-changes-for-vc-part-5/">Visual Studio 2010 changes for VC++ (part 5)</a></li>
<li>Task dialog support<br /><a href="http://mariusbancila.ro/blog/2009/03/10/task-dialog-in-mfc/">Task dialog in MFC</a></li>
<li>Restart manager support<br /><a href="http://mariusbancila.ro/blog/2009/03/08/restart-manager-in-mfc/">Restart manager in MFC</a></li>
</ul>
<p>In addition, here are some more articles about Visual C++ 2010 that I published on codeguru.com.</p>
<ul>
<li><a href="http://www.codeguru.com/cpp/v-s/article.php/c17001/">Changes to VC++ in Microsoft Visual Studio 2010</a></li>
<li><a href="http://www.codeguru.com/cpp/article.php/c17009/">Changes to the C++ Compiler in Microsoft Visual Studio 2010</a></li>
<li><a href="http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c17021/">Changes to MFC in Microsoft Visual Studio 2010</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/04/02/visual-studio-2010-changes-for-vc-summary/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2010 changes for VC++ (part 5)</title>
		<link>http://mariusbancila.ro/blog/2010/03/24/visual-studio-2010-changes-for-vc-part-5/</link>
		<comments>http://mariusbancila.ro/blog/2010/03/24/visual-studio-2010-changes-for-vc-part-5/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 21:10:48 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[deployment]]></category>
		<category><![CDATA[VC++]]></category>
		<category><![CDATA[VS2010]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=501</guid>
		<description><![CDATA[I this post I will talk about the deployment changes in VC++ 2010. When you deploy an application to another machine you have to install not only the application but all the libraries that it depends on. When you build with VC++, you have dependencies on CRT (C/C++ runtime) and possible on MFC and/or ATL. [...]]]></description>
			<content:encoded><![CDATA[<p>I this post I will talk about the deployment changes in VC++ 2010. When you deploy an application to another machine you have to install not only the application but all the libraries that it depends on. When you build with VC++, you have dependencies on CRT (C/C++ runtime) and possible on MFC and/or ATL.</p>
<p>Visual Studio 2005 introduced a new deployment model for Windows client applications based on <em>isolated applications</em> and <em>side-by-side assemblies</em>. Assemblies can be either <strong>shared</strong> (globally registered in the system, installed in the Global Assembly Cache – GAC folder in Windows – and available to all applications) or <strong>side-by-side</strong> (described with a manifest, distributed with the application and available only to that application).</p>
<p>In Visual C++ 2005, library assemblies (such as MFC, ATL, CRT) have been rebuilt as <em>shared side-by-side</em> assemblies and installed in the native assembly cache, WinSxS folder in Windows. That means they are not globally registered in the system, but are globally available to the applications that specify a dependency with a manifest file.</p>
<p>With VC++ 2005 or 2008 there are several options for deployment:</p>
<ul>
<li><strong>static linking</strong>: when you link your application statically against VC++ libraries (CRT, MFC or ATL) the application doesn&#8217;t have any dependencies so you don&#8217;t have to deploy any other VC++ DLLs to the target machine</li>
<li><strong>shared side-by-side assemblies</strong>: the VC++ DLLs are deployed in the WinSxS folder; this can be done either with the Visual C++ Redistributable Merge Modules or the Visual C++ Redistributable Package; the application requires a manifest file that describes the dependent DLLs and their version</li>
<li><strong>private assemblies</strong>: the VC++ DLLs are all installed in the same folder with the application; the application requires a manifest file</li>
</ul>
<p>When you deploy an application built with Visual Studio 2005 or 2008 a manifest file that describes the dependencies, whether you deployed these VC++ DLLs in the local folder or they where installed in the WinSxS folder. If the manifest is missing you get an error. The next image shows the error received when running an MFC application (called Wordpad2008) build with VC++ 2008 on another machine without a manifest. </p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/vs2010deplymentwordpad2008.png" title="VC++ 2008 application without a manifest" class="alignnone" width="741" height="379" /></p>
<p>Though the purpose of this change was to simplify deployment, the result was probably the opposite. As a result Microsoft changed deployment requirements in Visual C++ 2010. You can now deploy applications without a Fusion or satellite manifest. All you need to do is copy the VC++ dependent DLLs to the application folder and run. The next image shows an MFC application (called Wordpad2010) built with VC++ 2010 running on another machine, without a satellite assembly. No error occurs any more when trying to start the application, because local deployment no longer require a satellite manifest.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/vs2010deplymentwordpad2010.png" title="VC++ 2010 application without a manifest" class="alignnone" width="741" height="411" /></p>
<p>With VC++ 2010 there are several options for deployment:</p>
<ul>
<li><strong>static linking</strong>: same as earlier</li>
<li><strong>central deployment</strong>: the VC++ DLLs are deployed in the system32 folder; this is useful for updates, because Windows automatically identifies and updates the DLLs that are deployed here</li>
<li><strong>local deployment</strong>: the application executable and its dependent DLLs are all installed in the same folder; no manifest file is required.</li>
</ul>
<p>To find more information about deployment and manifest files I suggest these links:</p>
<ul>
<li><a href="http://www.codeguru.com/forum/showthread.php?t=408061">Visual C++ Application: How to use manifests and re-distributable assemblies?</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms235316.aspx">Choosing a Deployment Method (VC++ 2008)</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/dd293574%28VS.100%29.aspx">Deployment in Visual C++ 2010</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms235342.aspx">Troubleshooting C/C++ Isolated Applications and Side-by-side Assemblies</a></li>
<li><a href="http://www.grimes.demon.co.uk/workshops/fusWSThirteen.htm">.NET Fusion</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/03/24/visual-studio-2010-changes-for-vc-part-5/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2010 changes for VC++ (part 4)</title>
		<link>http://mariusbancila.ro/blog/2010/03/23/visual-studio-2010-changes-for-vc-part-4/</link>
		<comments>http://mariusbancila.ro/blog/2010/03/23/visual-studio-2010-changes-for-vc-part-4/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 08:08:11 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[MFC]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[ribbon]]></category>
		<category><![CDATA[VC++]]></category>
		<category><![CDATA[VS2010]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=498</guid>
		<description><![CDATA[VC++ Feature Pack that came with Visual Studio 2008 SP1 introduced support for the Office Fluent Ribbon. However, developers had to create ribbons entirely from code, because there was no support in the resource editor for that. Visual Studio 2010 comes with a visual designer for the ribbon. You can choose whether to use a [...]]]></description>
			<content:encoded><![CDATA[<p>VC++ Feature Pack that came with Visual Studio 2008 SP1 introduced support for the Office Fluent Ribbon. However, developers had to create ribbons entirely from code, because there was no support in the resource editor for that. Visual Studio 2010 comes with a visual designer for the ribbon.</p>
<p>You can choose whether to use a ribbon or a classical menu and toolbar when you create an application.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/ribbonnew.png" title="Use a ribbon instead of menu and toolbar" class="alignnone" width="627" height="532" /></p>
<p>By default, the created ribbon has one category (Home) and two panels with several commands.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/ribbondefault.png" title="Default ribbon" class="alignnone" width="365" height="180" /></p>
<p>The ribbon can be opened from the resource editor. There is a new category called Ribbon. By default the ribbon resource is called IDR_RIBBON. The description of the ribbon is kept in an XML file called <strong>ribbon.mfcribbon-ms</strong>, located in the res folder.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/ribbonresources.png" title="Ribbon in resource editor" class="alignnone" width="316" height="241" /></p>
<p>When the ribbon is opened, the toolbar displays controls that can be dragged and drop into the ribbon, including categories, context categories, panels, and a series of controls such as buttons, checkbox, edits, progress bar, slider, etc.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/ribbontoolbar.png" title="Ribbon toolbar" class="alignnone" width="301" height="516" /></p>
<p>There is support for several styles, Office like and Windows 7. These different styles can be seen in the following image.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/ribbonstyles.png" title="Ribbon styles" class="alignnone" width="521" height="733" /></p>
<p>The designer provides support for quick testing of the ribbon. On the Ribbon Editor toolbar there is a button called Test Ribbon that opens window with the ribbon. You can quickly see how it will look in the application, however, the commands are not available; clicking on the ribbon commands does not have any effect.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/ribbontestbutton.png" title="Ribbon designer test button" class="alignnone" width="369" height="210" /></p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/ribbontestlive.png" title="Ribbon live test" class="alignnone" width="521" height="400" /></p>
<p>You can add handlers for the ribbon commands just like you do for a menu or a toolbar. In Visual Studio 2010 this can be done with the class wizard.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/ribbonhandlers.png" title="Ribbon command handlers" class="alignnone" width="783" height="407" /></p>
<p>You can read more about the ribbon designed in <a href="http://msdn.microsoft.com/en-us/library/bb386089%28VS.100%29.aspx" target="_blank">MSDN</a> or the <a href="http://blogs.msdn.com/vcblog/archive/2009/10/01/ribbon-designer.aspx" target="_blank">VC++ Team&#8217;s Blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/03/23/visual-studio-2010-changes-for-vc-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2010 changes for VC++ (part 3)</title>
		<link>http://mariusbancila.ro/blog/2010/03/22/visual-studio-2010-changes-for-vc-part-3/</link>
		<comments>http://mariusbancila.ro/blog/2010/03/22/visual-studio-2010-changes-for-vc-part-3/#comments</comments>
		<pubDate>Mon, 22 Mar 2010 08:36:23 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[auto]]></category>
		<category><![CDATA[decltype]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[static_assert]]></category>
		<category><![CDATA[VS2010]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=491</guid>
		<description><![CDATA[Some of the important changs in Visual Studio 2010 in regard to VC++ are represented by the support in the C++ compiler of some of the features already approved for the new C++ standard, so far called C++0x. In this post I will give a short overview on then. static_assert I already wrote a post [...]]]></description>
			<content:encoded><![CDATA[<p>Some of the important changs in Visual Studio 2010 in regard to VC++ are represented by the support in the C++ compiler of some of the features already approved for the new C++ standard, so far called C++0x. In this post I will give a short overview on then.</p>
<p><strong>static_assert</strong></p>
<p>I already <a href="http://mariusbancila.ro/blog/2009/02/25/c-static_assert-a-niche-feature/">wrote a post</a> about this feature. At that time I considered it rather a niche feature. However, this looks much powerful in conjunction with the <a href="http://msdn.microsoft.com/en-us/library/bb982077.aspx">type traits classes</a> from TR1.</p>
<p>static_assert checks if an expression is true at compile time. If the expression if false a custom error message is displayed and the compilation fails. If the expression is true the declaration has no effect.</p>
<p>In the following example I create a comparison template function, that is used later to compare values.</p>
<pre class="prettyprint">
template < typename T >
bool CompareNumbers(T v1, T v2)
{
   return v1 > v2;
}

int main()
{
   bool ret1 = CompareNumbers(1, 20);
   bool ret2 = CompareNumbers("b", "a");

   return 0;
}
</pre>
<p>I want this function to be used only for integral types (the reason doesn&#8217;t matter) and I&#8217;d like the compiler to issue an error when used with any other type. Adding a static_assert check will generate a compilation error for the second call to the function, when passing strings.</p>
<pre class="prettyprint">
#include < type_traits >

template < typename T >
bool CompareNumbers(T v1, T v2)
{
   static_assert(std::tr1::is_integral< T >::value, "Type is not numeric");
   return v1 > v2;
}
</pre>
<pre class="prettyprint">
1>d:\marius\vc++\cpp0x\cpp0x.cpp(62): error C2338: Type is not numeric
1>          d:\marius\vc++\trainnings\cpp0x\cpp0x.cpp(75) : see reference to function template instantiation 'bool CompareNumbers<const char*>(T,T)' being compiled
1>          with
1>          [
1>              T=const char *
1>          ]
</pre>
<p><strong>auto</strong></p>
<p>If you are familiar with C#, this is the C++ equivalent of var. The keyword is used to deduce the type of a declared variable from its initialization expression. The initialization expression can be an assignment, direct initialization or operator new expression. It must be noted that the auto keyword is just a placeholder, not a type, and cannot be used with sizeof or typeid.</p>
<pre class="prettyprint">
auto i = 13;        // i is int
auto s = "marius";  // s is std::string
auto p = new foo(); // p is foo*

vector< int > numbers;
generate_n(back_inserter(numbers), 10, rand);
for(auto it = numbers.begin(); it != numbers.end(); ++it)
{
   cout << *it << endl;
}
</pre>
<p><strong>lambda expressions</strong></p>
<p>I already <a href="http://mariusbancila.ro/blog/2009/02/24/lambdas-in-c/">wrote about lambdas</a>, but I will give a short overview again. Again, if you are familiar with C# and .NET, this is the same concept as in .NET.</p>
<p>A lambda functions is a function object whose type is implementation dependent; its type name is only available to the compiler. The lambda expression is composed of several parts:</p>
<ul>
<li>lambda_introducer: this is the part that tells the compiler a lambda function is following. Inside the angled brackets a capture-list can be provided; this is used for capturing variables from the scope in which the lambda is created.</li>
<li>lambda-parameter-declaration: used for specifying the parameters of the lambda function.</li>
<li>lambda-return-type-clause: used for indicating the type returned by the lambda function. This is optional, because most of the time the compiler can infer the type. There are cases when this is not possible and then the type must be specified. For the example above, the return type (-> bool) is not necessary.
</li>
<li>compound-statement: this is the body of the lambda.</li>
</ul>
<pre class="prettyprint">
vector< int > numbers;
generate_n(back_inserter(numbers), 10, rand);

for_each(numbers.begin(), numbers.end(), [](int n) {cout << n << endl;});
</pre>
<p>Here <em>[]</em> is the lambda introducer, <em>(int n)</em> is the lambda parameter declaration, and <em>{cout << n << endl;}</em> is the lambda compound statement. There is no return type clause, because that is auto inferred by the compiler. There are cases when the compiler cannot deduce the return value and then it must be specified explicitly. A lambda expression is a syntactic shortcut for a functor. The code above is equivalent to:</p>
<pre class="prettyprint">
class functor_lambda
{
public:
   void operator()(int n) const
   {
      cout << n << endl;
   }
};

vector< int > numbers;
generate_n(back_inserter(numbers), 10, rand);

for_each(numbers.begin(), numbers.end(), functor_lambda());
</pre>
<p>Lambdas can capture variables from their scope by value, reference or both in any combination. In the example above, there was no value captured. This is a stateless lambda. On the other hand, a lambda that captures variables is said to have a state.</p>
<p><strong>rvalue references</strong></p>
<p>Stephan T. Lavavej wrote <a href="http://blogs.msdn.com/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx">the ultimate guide to rvalue references</a>. There is nothing more that can be said that is not already there. I strongly suggest you read his article to familiarize with this concept.</p>
<p>rvalue references are used to hold a reference to a rvalue or lvalue expression, and are introduced with &#038;&#038;. They enable the implementation of move semantics and perfect forwarding.</p>
<p>Move semantics enable transferring resources from one temporary object to another. This is possible because temporary objects (i.e. rvalues) are not referred anywhere else outside the expression in which they live. To implement move semantics you have to provide a move constructor and optionally a move assignment operator. The Standard Template Library was changed to take advantage of this feature. A classic example for the move semantics is represented by operation with sequences like vector or list. A vector allocates memory for a given number of objects. You can add elements to it and no re-allocation is done until the full capacity is reached. But when that happens, the vector has to reallocate memory. In this case it allocates a new larger chunk, copies all the existing content, and then releases the pervious memory. When an insertion operation needs to copy one element several things happen: a new element is created, its copy constructor is called, and then the old element is destroyed. With moves semantics, the allocation of a new element and its copy is no longer necessary, the existing element can be directly moved.</p>
<p>A second scenario where rvalue references are helpful is the perfect forwarding. The forwarding problem occurs when a generic function takes references as parameters and then needs to forward these parameters to another function. If a generic function takes a parameter of type const T&#038; and needs to call a function that takes T&#038;, it can't do that. So you need an overloaded generic function. What rvalue references enable is having one single generic function that takes arbitrary arguments and then forwards them to another function.</p>
<p><strong>decltype operator</strong></p>
<p>This is used to yield the type of an expression. Its primary purpose is for generic programming, in conjunction with auto, for return types of generic functions where the type depends on the arguments of the function. Here are several examples:</p>
<pre class="prettyprint">
double d = 42.0;     // decltype(i) yields double
const int&amp;&amp; f();     // decltype(f()) yields const int&amp;&amp;
struct foo {int i;}; // decltype(f.i) yields int (f being an object of type foo)
</pre>
<p>It can be used together with auto to declare late specified return type, with the alternative function declaration syntax, which is (terms in squared brackets indicate optional parts)</p>
<pre class="prettyprint">
auto function_name([parameters]) [const] [volatile] -> decltype(expression) [throw] {function_body};
</pre>
<p>In general, the expression use with decltype here should match the expression used in the return statement.</p>
<pre class="prettyprint">
struct Liters
{
   double value;
   explicit Liters(double val):value(val){}
};

struct Gallons
{
   double value;
   explicit Gallons(double val):value(val){}
};

ostream&amp; operator<<(ostream&amp; os, const Liters&amp; l)
{
   os << l.value << "l";
   return os;
}

ostream&amp; operator<<(ostream&amp; os, const Gallons&amp; g)
{
   os << g.value << "gal";
   return os;
}

Liters operator+(const Liters&amp; l1, const Liters&amp; l2)
{
   return Liters(l1.value + l2.value);
}

Gallons operator+(const Gallons&amp; g1, const Gallons&amp; g2)
{
   return Gallons(g1.value + g2.value);
}

Liters operator+(const Liters&amp; l, const Gallons&amp; g)
{
   return Liters(l.value + g.value*3.785);
}

Gallons operator+(const Gallons&amp; g, const Liters&amp; l)
{
   return Gallons(g.value + l.value*0.264);
}

template < typename T1, typename T2 >
auto Plus(T1&amp;&amp; v1, T2&amp;&amp; v2) -> decltype(forward< T1 >(v1) + forward< T2 >(v2))
{
   return forward< T1 >(v1) + forward< T2 >(v2);
}

int main()
{
   cout << Plus(l1, l2) << endl;
   cout << Plus(g1, g2) << endl;
   cout << Plus(l1, g1) << endl;
   cout << Plus(g2, l2) << endl;

   return 0;
}
</pre>
<p>The result of the execution is:</p>
<pre class="prettyprint">
15l
30gal
42.85l
22.64gal
</pre>
<p>When function Plus is called with arguments of the same type, the result is that type. But when the arguments differ, the resulting type is also different. In this example, when the first argument is Liters and second is Gallons, the result type must be Liters and the opposite. It is possible to do this without decltype, but the solution requires explicit specification of the resulting type.</p>
<pre class="prettyprint">
template < typename T, typename T1, typename T2 >
T Plus(T1&amp;&amp; v1, T2&amp;&amp; v2)
{
   return forward< T1 >(v1) + forward< T2 >(v2);
}

int main()
{
   cout << Plus<Liters>(l1, l2) << endl;
   cout << Plus<Gallons>(g1, g2) << endl;
   cout << Plus<Liters>(l1, g1) << endl;
   cout << Plus<Gallons>(g2, l2) << endl;

   return 0;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/03/22/visual-studio-2010-changes-for-vc-part-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2010 Changes for VC++ (part 2)</title>
		<link>http://mariusbancila.ro/blog/2010/03/18/visual-studio-2010-changes-for-vc-part-2/</link>
		<comments>http://mariusbancila.ro/blog/2010/03/18/visual-studio-2010-changes-for-vc-part-2/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 08:45:13 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Browsing]]></category>
		<category><![CDATA[ClassWizard]]></category>
		<category><![CDATA[IntelliSense]]></category>
		<category><![CDATA[VC++]]></category>
		<category><![CDATA[VS2010]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=487</guid>
		<description><![CDATA[In my previous post I talked about the new build system for VC++ from Visual Studio 2010, which is MSBuild and the support for multi-targetting. In this post I will talk about changes to IntelliSense and browsing. If you go back to the example I was providing in the first post, with the two identical [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://mariusbancila.ro/blog/2010/03/17/visual-studio-2010-changes-for-vc-part-1/">previous post</a> I talked about the new build system for VC++ from Visual Studio 2010, which is MSBuild and the support for multi-targetting. In this post I will talk about changes to IntelliSense and browsing.</p>
<p>If you go back to the example I was providing in the first post, with the two identical projects created with Visual Studio 2008 and Visual Studio 2010, a second important thing to notice in the comparison of the two solution is that the infamous .NCB file is no longer present in Visual Studio 2010 solution. Instead there is a new file with extension .SDF. This is not just a renaming of the extension, the entire Intellisense for Visual C++ was redesigned in Visual Studio 2010. This is a SQL Server Database file, possible to be opened even in Visual Studio (if one wants to check its content).</p>
<p>In the previous versions of Visual C++, each time you modified a header, the entire solution was reparsed, in which time it was very hard to use the environment. Moreover, the IntelliSense database file (the .NCB file) never seem to shrink, only increased in size, and it could get corrupted from time to time. In the new version, files are parsed on the background, and the IDE does not read all the files, only the current translation unit (which is a source file and all the headers it includes directly and indirectly). As a result, the operation is much swifter and less error prone.</p>
<p>There is also a new disk folder called <strong>iPCH</strong> in the new solution. This is the storing location for IntelliSense support files and browsing database files (SDF).</p>
<p><strong>#include auto completion</strong></p>
<p>Part of the new IntelliSense and Browsing experience, the #include keyword supports auto-completion for the header files. That means that after typing #include, the IDE displays a list of available headers, filter by their name as you type. The following image shows this.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/wordpad2010autoinclude.png" title="#include auto completion" class="alignnone" width="667" height="208" /></p>
<p><strong>Call Hierarchy</strong></p>
<p>This feature enables navigation through the code, showing the calls to and from a selected method, constructor or property. When selecting a call in the hierarchy window it shows the code where the call is made.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/wordpad2010callh.png" title="Call hierarchy window" class="alignnone" width="842" height="240" /></p>
<p><strong>Red Squiggles</strong></p>
<p>This is a feature that enables highlighting syntactic and semantic errors with a red squiggle line. Hovering the mouse over the line will show a balloon with the error message. The same error is also listed in the Error List window.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/wordpad2010squiggles.png" title="Reg quiggles for errors" class="alignnone" width="529" height="164" /></p>
<p><strong>Find All References</strong></p>
<p>In the previous versions, this features displayed only the compiler verified results for a search. If you searched for a function M member of a class C it only returned the references where function M was used in the context of C. The new version allows two types of search: one that is focus on speed, and returns all the matches for a symbol regardless the context (but it&#8217;s a narrowed search than the one performed with Find in Files), and one that is focused on accuracy and returns only the compiler verified results (i.e. the ones that match the search context).</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/wordpad2010findsym.png" title="Find all References window" class="alignnone" width="770" height="240" /></p>
<p><strong>Class Wizard</strong></p>
<p>Yet another important change is the famous and acclaimed class wizard from VC6, that was dropped in Visual Studio 2002, and was now brought back in Visual Studio 2010.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/wordpad2010classwiz.png" title="Class wizard" class="alignnone" width="816" height="685" /></p>
<p>If you are (or were) familiar with VC6 you know what the Class Wizard is. In Visual Studio 2010 it features basically the same functionality, except that it is improved with search functionality. You can search for command, messages, virtual functions, members or methods. This is great because might not know the exact name of a message or a function, but searching allows you to quickly get it with only typing part of the name. For those not familiar with VC6 this is a single point to add or remove commands, message handlers, virtual functions, member variables and methods. This was a favorite feature in VC6 for a lot of people and there was a constant pressure on Microsoft to bring it back, so here it is.</p>
<p>All these features are detailed in MSDN and on the VC++ Team blog. I suggest several additional readings:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/dd409859%28VS.100%29.aspx" target="_blank">Call Hierarchy</a></li>
<li><a href="http://blogs.msdn.com/vcblog/archive/2009/06/01/c-gets-squiggles.aspx" target="_blank">C++ Gets Squiggles!</a></li>
<li><a href="http://blogs.msdn.com/vcblog/archive/2009/07/13/intellisense-and-browsing-with-c-0x.aspx" target="_blank">Intellisense and Browsing with C++0x</a></li>
<li><a href="http://blogs.msdn.com/vcblog/archive/2009/11/17/improvements-to-find-all-references-in-visual-studio-2010.aspx" target="_blank">Improvements to Find all references in Visual Studio 2010</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/03/18/visual-studio-2010-changes-for-vc-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2010 Changes for VC++ (part 1)</title>
		<link>http://mariusbancila.ro/blog/2010/03/17/visual-studio-2010-changes-for-vc-part-1/</link>
		<comments>http://mariusbancila.ro/blog/2010/03/17/visual-studio-2010-changes-for-vc-part-1/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 09:02:34 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[msbuild]]></category>
		<category><![CDATA[VC++]]></category>
		<category><![CDATA[VS2010]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=483</guid>
		<description><![CDATA[The new version of Visual Studio, called Visual Studio 2010 comes with a series of changes for Visual C++. This includes a new build system, new project system, multi-targeting, new IntelliSense, support in MFC for new controls, new additions to the C++ compiler (which were already approved for C++0x), new deployment model, and others. In [...]]]></description>
			<content:encoded><![CDATA[<p>The new version of Visual Studio, called Visual Studio 2010 comes with a series of changes for Visual C++. This includes a new build system, new project system, multi-targeting, new IntelliSense, support in MFC for new controls, new additions to the C++ compiler (which were already approved for C++0x), new deployment model, and others. In this post I will talk about the new build system and multi-targeting.</p>
<p>In order to show the changes I will create two simple projects, one in Visual Studio 2008, called Wordpad 2008, and one in Visual Studio 2010, called Wordpad 2010. These would be simple MFC single document applications. The image bellow shows the two solutions opened in Solution Explorer.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/wordpadsolsxs.png" title="Projects in Solution Explorer, side by side" class="alignnone" width="645" height="500" /></p>
<p>As you can see both versions contain the same solutions file (only the suffix in the name differs). The next image shows the files on disk, in comparison for the two solutions.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/wordpadsxs.png" title="Solutions on disk, side by side" class="alignnone" width="828" height="432" /></p>
<p><strong>MS-Build System</strong></p>
<p>The first thing to notice (though it might not be the obvious) is that the project file extension was modified. In Visual Studio 2008 it is called .vcproj, but in Visual Studio 2010 is called .vcxproj. Not only the extension changed, but also the content of the file. This is because in Visual Studio 2010, Visual C++ build system was changed from <a href="http://msdn.microsoft.com/en-us/library/hw9dzw3c%28VS.80%29.aspx" target="_blank">VCBuild</a> to <a href="http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx" target="_blank">MSBuild</a>. This build engine was already used for the languages targeting the .NET framework.</p>
<p>MSBuild uses XML project files, and the most important elements of a project are:</p>
<ul>
<li><strong>Items</strong>: units of input into the build system, grouped into item collections, which can be used as parameters to the tasks, using the syntax <em>@(ItemCollectionName)</em>. Examples of items from the Wordpad2010 project:
<pre class="prettyprint">
  < ItemGroup >
    < ClInclude Include="MainFrm.h" / >
    < ClInclude Include="Resource.h" / >
    < ClInclude Include="stdafx.h" / >
    < ClInclude Include="targetver.h" / >
    < ClInclude Include="Wordpad2010.h" / >
    < ClInclude Include="Wordpad2010Doc.h" / >
    < ClInclude Include="Wordpad2010View.h" / >
  < /ItemGroup >
</pre>
</li>
<li><strong>Properties</strong>: pairs of key/value used to configure the builds. The value of a property can be changed after it was defined. They can be referred in the project file using the syntax <em>$(PropertyName)</em>. Examples of properties from the Wordpad2010 project.
<pre class="prettyprint">
  < PropertyGroup Label="Globals" >
    < ProjectGuid >{1E7DC2AA-8CAC-44A8-98F6-DE69249AD30C}< /ProjectGuid >
    < RootNamespace >Wordpad2010< /RootNamespace >
    < Keyword >MFCProj< /Keyword >
  < /PropertyGroup >
</pre>
</li>
<li><strong>Tasks</strong>: reusable units of executable code used to perform builds. Example of tasks can be compiling input files, linking, running external tools. Tasks can be reused in different projects.</li>
<li><strong>Targets</strong>: represent groupings of tasks in a particular order and expose parts of the project file as entry points into the build system.</li>
</ul>
<p>You can get a deeper overview on the <a href="http://msdn.microsoft.com/en-us/library/ms171452.aspx" target="_blank">MSBuild</a> engine here.</p>
<p>Another thing to notice is the presence of a file called Wordpad2010.vcxproj.filters. This file defines the solution explorer tree with the files contained in the project. This used to be a part of the file project, but in Visual Studio 2010 it was moved into a separate file. The reason is to keep the project file only for the build, not for the organization of the project.</p>
<p>The user specific settings used to be stored in a file called <strong><em>ProjectName</em>.vcproj.<em>fullyqualifiedusername</em>.user</strong>. Now there is a new file called <strong><em>ProjectName</em>.vcxproj.user</strong>.</p>
<p>You can read more about these changes in <a href="http://msdn.microsoft.com/en-us/library/ee862524%28VS.100%29.aspx" target="_blank">MSDN</a>.</p>
<p><strong>Multi-targeting</strong></p>
<p>Visual Studio 2008 came to support for multi-targeting of the .NET framework, not only for C# and VB.NET, but also for C++/CLI. In addition to that, Visual Studio 2010 comes with support for native multi-targeting.</p>
<p>The managed multi-targeting allows to target different versions of the .NET framework for mixed-mode applications. By default the target version is the latest, 4.0. This can only be changed manually in the project file. The support for changing this from the IDE was not included in this version. Actually it was dropped, because in Visual Studio 2008 this was possible.</p>
<pre class="prettyprint">
  < PropertyGroup Label="Globals" >
    < ProjectGuid >{AB3D9231-F8B6-4EAD-A15B-C792977AB26E}< /ProjectGuid >
    < RootNamespace >MixedModeDemo< /RootNamespace >
    < TargetFrameworkVersion >v3.5< /TargetFrameworkVersion >
    < Keyword >MFCDLLProj< /Keyword >
  < /PropertyGroup >
</pre>
<p>The native multi-targeting allows to use different versions of the tools and libraries to build (native) C++ projects. Of course, you must have the targeted toolset installed on your machine, in order to do that. You can define different configurations that target different versions of the toolsets. The targeted toolset can be changed from project&#8217;s properties page, General, Platform Toolset. The following image shows the available options on a machine with Visual Studio 2008 SP1 and Visual Studio 2010 installed side by side.</p>
<p><img alt="" src="/blog/wp-content/uploads/2010/03/wordpad2010propsgen.png" title="Platform toolset property in project&#039;s properties" class="alignnone" width="618" height="289" /></p>
<p>It is possible to target the previous version, 2008, 2005, 2003 and 2002. In theory it&#8217;s possible to target even VC6, but there is no support from Microsoft for that.</p>
<p>I suggest to read more about native multi-targeting <a href="http://blogs.msdn.com/vcblog/archive/2009/12/08/c-native-multi-targeting.aspx" target="_blank">here</a>, and about managed multi-targeting, for mixed-mode applications, <a href="http://blogs.msdn.com/visualstudio/archive/2009/11/22/framework-multi-targeting-for-vc-projects.aspx" target="_blank">here</a>.</p>
<p>In a next post I will talk about the changes to IntelliSense and browsing experience.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/03/17/visual-studio-2010-changes-for-vc-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Helpers For Multithreading in C++</title>
		<link>http://mariusbancila.ro/blog/2010/02/01/helpers-for-multithreading-cpp/</link>
		<comments>http://mariusbancila.ro/blog/2010/02/01/helpers-for-multithreading-cpp/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 20:32:17 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Parallel Programming]]></category>
		<category><![CDATA[C++ multithreads threads concurrency]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=466</guid>
		<description><![CDATA[On of the most important challenges nowadays in programming is concurrency. If we don&#8217;t learn to write programs that are able to run on multiple cores the progress in hardware will be pointless. But when you run multiple threads for various processing you might face the situation when you have to write over and over [...]]]></description>
			<content:encoded><![CDATA[<p>On of the most important challenges nowadays in programming is concurrency. If we don&#8217;t learn to write programs that are able to run on multiple cores the progress in hardware will be pointless. But when you run multiple threads for various processing you might face the situation when you have to write over and over again same or similar code for creating the threads, setting up the parameters for the threads, joining the threads, checking the result, cleaning-up, etc.</p>
<p>In this post I will show how you can create some helpers in C++ to simplify this process. This is not going to be a full solution, neither a solution that fits all needs, but can be a start.</p>
<p>What I would like to have is a helper class that will take care of:</p>
<ul>
<li>finding how many threads can run (considering each available core can run a thread)</li>
<li>creating and starting the threads</li>
<li>joining the threads</li>
<li>checking the result of the threads execution</li>
<li>cleaning up</li>
</ul>
<p>The class show bellow does just that.</p>
<pre class="prettyprint">
#include < windows.h >

class ThreadHelper
{
	LPVOID* m_Params;
	int m_ThreadsNo;

private:
	int GetProcessorsCount()
	{
		SYSTEM_INFO info;
		::GetSystemInfo(&amp;info);
		return info.dwNumberOfProcessors;
	}

public:
	ThreadHelper()
	{
		m_ThreadsNo = GetProcessorsCount();

		m_Params = new LPVOID[m_ThreadsNo];
		for(int i = 0; i < m_ThreadsNo; ++i)
			m_Params[i] = NULL;
	}

	ThreadHelper(int threadsNo)
	{
		if(threadsNo < 1)
			m_ThreadsNo = GetProcessorsCount();
		else
			m_ThreadsNo = threadsNo;

		m_Params = new LPVOID[m_ThreadsNo];
		for(int i = 0; i < m_ThreadsNo; ++i)
			m_Params[i] = NULL;
	}

	~ThreadHelper()
	{
		delete [] m_Params;
	}

	int GetThreadsNo() const {return m_ThreadsNo;}
	bool SetThreadParams(int threadIndex, LPVOID lpData)
	{
		if(threadIndex >= 0 &#038;&#038; threadIndex < m_ThreadsNo)
		{
			m_Params[threadIndex] = lpData;
			return true;
		}

		return false;
	}

	bool Run(LPTHREAD_START_ROUTINE threadProc, BOOL startImmediatelly, DWORD timeout = INFINITE)
	{
		bool success = false;

		HANDLE* hThreads = new HANDLE[m_ThreadsNo];
		DWORD* dwThreadIds = new DWORD[m_ThreadsNo];

		bool allThreadsOK = true;

		// create the threads
		for(int i = 0; i < m_ThreadsNo &amp;&amp; allThreadsOK; ++i)
		{
			hThreads[i] = ::CreateThread(
				NULL,
				0,
				threadProc,
				m_Params[i],
				startImmediatelly ? 0 : CREATE_SUSPENDED,
				&amp;dwThreadIds[i]);

			if(hThreads[i] == NULL)
			{
				for(int j = 0; j < i; ++j)
				{
					::CloseHandle(hThreads[j]);
				}

				allThreadsOK = false;
			}
		}

		if(allThreadsOK)
		{
			// start the threads if they were suspended first
			if(!startImmediatelly)
			{
				for(int i = 0; i < m_ThreadsNo; ++i)
				{
					::ResumeThread(hThreads[i]);
				}
			}

			// wait for all threads
			DWORD joinret = ::WaitForMultipleObjects(
				m_ThreadsNo,
				hThreads,
				TRUE,
				timeout);

			if(joinret == WAIT_FAILED)
			{

			}
			else if(joinret = WAIT_TIMEOUT)
			{

			}
			else if(joinret >= WAIT_OBJECT_0 &amp;&amp; joinret < WAIT_OBJECT_0 + m_ThreadsNo)
			{
				success = true;
			}
			else if(joinret >= WAIT_ABANDONED_0 &amp;&amp; joinret < WAIT_ABANDONED_0 + m_ThreadsNo)
			{

			}

			// close the thread handles
			for(int i = 0; i < m_ThreadsNo; ++i)
			{
				::CloseHandle(hThreads[i]);
			}
		}

		delete [] hThreads;
		delete [] dwThreadIds;

		return success;
	}
};
</pre>
<p>This helper class contains:</p>
<ul>
<li>one parameter-less constructor that identifies the number of available processors and sets the threads count equal to the processors count</li>
<li>one constructor that takes the number of threads that should be created</li>
<li>one method (SetThreadParams) for setting the parameters for each thread that will be created</li>
<li>one method (Run) that creates and runs the thread, waits for them and checks the result of the execution</li>
</ul>
<p>As you can see the Run() method is simplistic. It does not handle for instance timed out or abandoned thread executions. Also it joins all threads, waiting until all of them finished execution. A more flexible method could wait only until the first thread finishes and then maybe closes the other threads. But as I said, this is a sample and not a complete solution.</p>
<p>Having this helper set up, I will start several threads to find the prime numbers in a sequence and print them in the console. </p>
<p>The following function computes whether a number is prime/</p>
<pre class="prettyprint">
#include < cmath >

bool IsPrime(int number)
{
	const int max = static_cast< int >(
		std::sqrt(static_cast< double >(number))) + 1;

	for (int i=2; i!=max; ++i)
	{
		if (number % i == 0) return false;
	}

	return true;
}
</pre>
<p>The thread procedure will run through a sub-sequence of a vector of integers and verify if each element is prime. I will use the following structure to pass the sequence bounds to the thread procedure:</p>
<pre class="prettyprint">
struct vector_bounds
{
	std::vector< int >::const_iterator begin;
	std::vector< int >::const_iterator end;
};
</pre>
<p>The thread procedure could look like this:</p>
<pre class="prettyprint">
static CRITICAL_SECTION cs;

DWORD WINAPI FindPrimes(LPVOID lpData)
{
	vector_bounds* bounds = static_cast< vector_bounds* >(lpData);
	if(bounds == NULL)
		return 1;

	for(std::vector< int >::const_iterator cit = bounds->begin;
		cit != bounds->end; ++cit)
	{
		if(IsPrime(*cit))
		{
			EnterCriticalSection(&amp;cs);

			std::cout << *cit << std::endl;

			LeaveCriticalSection(&amp;cs);
		}
	}

	return 0;
};
</pre>
<p>To print to the console a locking mechanism is necessary, otherwise prints from two different threads could collide. The critical section will be initialized before the threads are started.</p>
<p>What remains to be done is generating a sequence of integers, setting up the parameters with the sequence bounds for each thread and run the threads using the helper.</p>
<pre class="prettyprint">
int main()
{
	// generate some random numbers
	srand((unsigned long)time(NULL));
	std::vector< int > numbers;
	std::generate_n(std::back_inserter(numbers), 1000, rand);

	// create the thread helper
	ThreadHelper helper(4);
	int threads = helper.GetThreadsNo();

	// create the parameters for the threads
	std::vector< vector_bounds > params;
	std::vector< int >::const_iterator begin = numbers.begin();
	size_t partitionsize = numbers.size()/threads;

	for(int i = 0; i < threads; ++i)
	{
		vector_bounds bound;
		bound.begin = begin;
		bound.end = (i == threads - 1) ? numbers.end() : begin + partitionsize;
		params.push_back(bound);

		begin = bound.end;
	}

	for(int i = 0; i < threads; ++i)
		helper.SetThreadParams(i, &amp;params[i]);

	// run the threads
	InitializeCriticalSection(&amp;cs);

	std::cout << "start running..." << std::endl;

	bool success = helper.Run(FindPrimes, FALSE);

	std::cout << "finished " << (success? "successfully" : "failed") << std::endl;

	DeleteCriticalSection(&amp;cs);

	return 0;
}
</pre>
<p>Having this threads helper class, what I need to do when running some processing in several threads is:</p>
<ul>
<li>setup thread parameters (if the case)</li>
<li>write the thread procedure</li>
<li>create a ThreadHelper object and initialize it</li>
<li>run the threads and collect the results</li>
</ul>
<p>The helper class prevents writing same code over and over again and helps focusing on the most important tasks: writing the thread procedure. As I said earlier it is not a full solution, nor one that fits all scenarios, but you can develop it to suit your needs.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2010/02/01/helpers-for-multithreading-cpp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New MFC Toolbar Controls in Visual Studio 2010</title>
		<link>http://mariusbancila.ro/blog/2009/11/01/new-mfc-toolbar-controls-in-vs-2010/</link>
		<comments>http://mariusbancila.ro/blog/2009/11/01/new-mfc-toolbar-controls-in-vs-2010/#comments</comments>
		<pubDate>Sun, 01 Nov 2009 21:57:01 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[CTPs & Betas]]></category>
		<category><![CDATA[MFC]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[controls]]></category>
		<category><![CDATA[designer]]></category>
		<category><![CDATA[toolbar]]></category>
		<category><![CDATA[VS2010]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=386</guid>
		<description><![CDATA[With VC++ Feature Pack Microsoft has added new classes to MFC to provide support for new controls. However, these controls were not available from the designer. One had to manually wrote all the code for enabling an application to use these controls. Visual Studio 2010 Beta 2, released a couple of weeks ago, provides support [...]]]></description>
			<content:encoded><![CDATA[<p>With VC++ Feature Pack Microsoft has added new classes to MFC to provide support for new controls. However, these controls were not available from the designer. One had to manually wrote all the code for enabling an application to use these controls. Visual Studio 2010 Beta 2, released a couple of weeks ago, provides support in the designer for these controls. </p>
<div class="wp-caption alignnone" style="width: 249px"><img alt="MFC controls in the Toolbar" src="/blog/wp-content/uploads/2009/11/mfcnewcontrols_toolbar.png" title="MFC controls in the Toolbar" width="239" height="251" /><p class="wp-caption-text">MFC controls in the Toolbar</p></div>
<p>Here is a screen shot of a dialog application with these controls:</p>
<div class="wp-caption alignnone" style="width: 772px"><img alt="New MFC Controls" src="/blog/wp-content/uploads/2009/11/mfcnewcontrols_demo.png" title="New MFC Controls" width="762" height="571" /><p class="wp-caption-text">New MFC Controls</p></div>
<p>The controls are:</p>
<ul>
<li><strong>Color button</strong> (CMFCColorButton): represent a color picker control allowing users to select a color</li>
<li><strong>Font combo box</strong> (CMFCFontComboBox) : represent a combo control that displays a list of fonts available in the system</li>
<li><strong>Edit browse</strong> (CMFCEditBrowseCtrl): an editable control with a button that displays a dialog for selecting a file or a folder</li>
<li><strong>Visual Studio list box</strong> (CVSListBox): an editable list control with buttons for adding, removing or rearranging items in the list</li>
<li><strong>Masked edit</strong> (CMFCMaskedEdit): a masked edit control that has a string template representing the structure of the allowed input, which is validated against the value provided by the user</li>
<li><strong>Menu button</strong> (CMFCMenuButton): displays a pop-up menu (from a menu resource) and reports the command selected by the user</li>
<li><strong>Property grid</strong> (CMFCPropertyGridCtrl): an editable property grid control</li>
<li><strong>Shell list</strong> (CMFCShellListCtrl): a list control that displays the files and folders from you system just list Windows Explorer list view does</li>
<li><strong>Shell tree</strong> (CMFCShellTreeCtrl): a tree control that displays the folder from your system just like the Windows Explorer folder view does</li>
<li><strong>Link control</strong> (CMFCLinkCtrl): is a special button that has the appearance of a hyperlink and invokes the target link when pressed</li>
</ul>
<p>Not all the properties for these controls are available from the designer. For instance the properties list still needs hand coding, it is not possible to select a menu resource for the menu button nor the starting point for the shell tree and list. However, having them available in the toolbar is a good step forward.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2009/11/01/new-mfc-toolbar-controls-in-vs-2010/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
