<?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>CodeDread Blog &#187; C++</title>
	<atom:link href="http://www.codedread.com/blog/archives/category/technology/software/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.codedread.com/blog</link>
	<description></description>
	<lastBuildDate>Mon, 02 Jan 2012 15:30:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>On The Merits Of Const&#8230;</title>
		<link>http://www.codedread.com/blog/archives/2008/01/30/on-the-merits-of-const/</link>
		<comments>http://www.codedread.com/blog/archives/2008/01/30/on-the-merits-of-const/#comments</comments>
		<pubDate>Thu, 31 Jan 2008 00:23:47 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.codedread.com/archives/2008/01/30/on-the-merits-of-const/</guid>
		<description><![CDATA[A short post about using const in C++. Consider the following 3 for-loops in C/C++: /* Loop 1: */ for(int i = 0; i &#60; getSomeValue(); ++i) { &#8230;lots of stuff in here&#8230; } /* Loop 2: */ int n = getSomeValue(); for(int i = 0; i &#60; n; ++i) { &#8230;lots of stuff in [...]]]></description>
			<content:encoded><![CDATA[<p>A short post about using const in C++.  <span id="more-424"></span></p>
<p>Consider the following 3 for-loops in C/C++:</p>
<div class="code">
<p>/* Loop 1: */</p>
<p>for(int i = 0; i &#60; getSomeValue(); ++i) { &#8230;lots of stuff in here&#8230; }</p>
<p>/* Loop 2: */</p>
<p>int n = getSomeValue();</p>
<p>for(int i = 0; i &#60; n; ++i) { &#8230;lots of stuff in here&#8230; }</p>
<p>/* Loop 3: */</p>
<p>const int n = getSomeValue();</p>
<p>for(int i = 0; i &#60; n; ++i) { &#8230;lots of stuff in here&#8230; }</p>
</div>
<p>Best Practice:  If the value of &#8216;n&#8217; is not supposed to change throughout the lifetime of the loop, then I think everyone can agree that using const in Loop 3 is a best practice.  This helps ensure that some other coder doesn&#8217;t muck about with the loop&#8217;s end condition inside the loop (since it will be flagged with a compiler error).</p>
<p>Optimization: It makes sense that, in general, Loop 2 would execute faster than Loop 1.  But I was curious if a compiler could optimize Loop 3 to make it run faster than Loop 2?  It&#8217;s been awhile since I looked at any assembly output, and my compiler theory has always been rather weak, so I thought I&#8217;d throw the question out there in case anyone has a clue&#8230;</p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2008/01/30/on-the-merits-of-const/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>C++ STL: Safely Removing Items From A Container</title>
		<link>http://www.codedread.com/blog/archives/2007/11/30/c-stl-safely-removing-items-from-a-container/</link>
		<comments>http://www.codedread.com/blog/archives/2007/11/30/c-stl-safely-removing-items-from-a-container/#comments</comments>
		<pubDate>Fri, 30 Nov 2007 22:21:26 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://blog.codedread.com/archives/2007/11/30/c-stl-safely-removing-items-from-a-container/</guid>
		<description><![CDATA[A short article about removing items from a standard C++ container. When using the C++ Standard Template Library, one has to be careful not to invalidate iterators in a container that you&#8217;re iterating over. If that makes any sense to you, then A colleague of mine had code like this: class TaskList { &#160;&#160;vector&#60;Task*> mTasks; [...]]]></description>
			<content:encoded><![CDATA[<p>A short article about removing items from a standard C++ container.  <span id="more-411"></span></p>
<p>When using the C++ Standard Template Library, one has to be careful not to invalidate iterators in a container that you&#8217;re iterating over.  If that makes any sense to you, then <!--more--></p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
<p>A colleague of mine had code like this:</p>
<p><code></p>
<p>class TaskList {</p>
<p>&#160;&#160;vector&#60;Task*> mTasks;</p>
<p>&#160;&#160;typedef vector&#60;Task*>::iterator TaskIter;</p>
<p>&#160;</p>
<p>&#160;&#160;void removeTask(Task* t) {</p>
<p>&#160;&#160;&#160;&#160;TaskIter it = find(mTasks.begin(),mTasks.end(),t);</p>
<p>&#160;&#160;&#160;&#160;if(it != mTasks.end()) { mTasks.erase(it); }</p>
<p>&#160;&#160;}</p>
<p>&#160;</p>
<p>&#160;public:</p>
<p>&#160;&#160;void addTask(Task* t) { mTasks.push_back(t); }</p>
<p>&#160;</p>
<p>&#160;&#160;void processQueue() {</p>
<p>&#160;&#160;&#160;&#160;for(TaskIter loopit=mTasks.begin();loopit!=mTasks.end();++loopit) {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;Task* task = *loopit;</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;if(task->isNotDone()) {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;task->doSomething();</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;}</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;else {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;removeTask(task);</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;}</p>
<p>&#160;&#160;&#160;&#160;}</p>
<p>&#160;&#160;}</p>
<p>};</p>
<p></code></p>
<p>You might be surprised to hear that the program crashed when the first task had to be removed.  The reason is that the removeTask() function erases an item out the collection which invalidates the iterator loopit.  When the for-loop tries to increment the iterator, we get <i>unexpected results</i>.</p>
<p>This is a frustrating problem, but it can be solved.  In short you have to:</p>
<ul>
<li>grab the iterator that is returned from the erase operation</li>
<li>set your loop iterator to that returned iterator</li>
<li>change from a for-loop to a while-loop (to ensure that your loop iterator is not incremented when a task is removed)</li>
</ul>
<p>Here is the modified code:</p>
<p><code></p>
<p>&#160;&#160;TaskIter removeTask(Task* t) {</p>
<p>&#160;&#160;&#160;&#160;TaskIter it = find(mTasks.begin(); mTasks.end(), t);</p>
<p>&#160;&#160;&#160;&#160;if(it != mTasks.end()) { it = mTasks.erase(it); }</p>
<p>&#160;&#160;&#160;&#160;return it;</p>
<p>&#160;&#160;}</p>
<p>&#160;</p>
<p>&#160;&#160;void processQueue() {</p>
<p>&#160;&#160;&#160;&#160;TaskIter loopit = mTasks.begin();</p>
<p>&#160;&#160;&#160;&#160;while(loopit != mTasks.end()) {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;Task* task = *loopit;</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;if(task->isNotDone()) {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;task->doSomething();</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;++loopit;</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;}</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;else {</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;loopit = removeTask(task);</p>
<p>&#160;&#160;&#160;&#160;&#160;&#160;}</p>
<p>&#160;&#160;&#160;&#160;}</p>
<p>&#160;&#160;}</p>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2007/11/30/c-stl-safely-removing-items-from-a-container/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Bridging The Gap Cleanly: Setting Up LuaBridge</title>
		<link>http://www.codedread.com/blog/archives/2007/11/16/bridging-the-gap-cleanly-setting-up-luabridge/</link>
		<comments>http://www.codedread.com/blog/archives/2007/11/16/bridging-the-gap-cleanly-setting-up-luabridge/#comments</comments>
		<pubDate>Sat, 17 Nov 2007 02:44:08 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.codedread.com/archives/2007/11/16/bridging-the-gap-cleanly-setting-up-luabridge/</guid>
		<description><![CDATA[Inspired by Rob, I decided I&#8217;d take a crack at embedding Lua scripting in a couple C++ projects that I&#8217;m working on. Rob has gone the ultimate route of using SWIG, but when I was starting to do some research, I stumbled upon Luabridge, a library that attempts to do all the interface binding using [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by <a href="http://www.latenightpc.com/blog/archives/2007/11/06/starting-a-simple-example-using-lua-and-sdl-in-c/">Rob</a>, I decided I&#8217;d take a crack at embedding Lua scripting in a couple C++ projects that I&#8217;m working on.  Rob has gone the ultimate route of using <a href="http://www.latenightpc.com/blog/archives/2007/11/08/using-swig-to-connect-c-to-lua/">SWIG</a>, but when I was starting to do some research, I stumbled upon <a href="http://luabridge.sourceforge.net/">Luabridge</a>, a library that attempts to do all the interface binding using C++ templates.  This sounds like more fun to me &#8211; even if I can&#8217;t later use it for Scheme scripts or whatever in the future.<span id="more-407"></span></p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
<div id="DownloadLua">
<h3>Downloading Lua</h3>
<p>The first step is to install <a href="http://www.lua.org/">Lua</a> itself.  Download the latest (Lua 5.1.2) from <a href="http://www.lua.org/ftp/">here</a>.  Then unzip the package (I used c:\ so it unrolled into c:\lua-5.1.2).</p>
</div>
<div id="BuildLua">
<h3>Bulding Lua</h3>
<p>Next it&#8217;s time to build Lua.  I originally used Visual Studio .NET 2005 for this, so I went to Start > Program > Microsoft Visual Studio 2005 > Visual Studio Tools > Visual Studio 2005 Command Prompt.  This is a command prompt window with all environment variables set up properly to compile and link from the command line.  In this command prompt window, I went to c:\lua-5.1.2\ and typed:  etc\luavs.bat.  This invoked a batch file that built the Lua libraries.  The files were plopped into c:\lua-5.1.2\src:  lua51.dll and lua51.lib. </p>
<p>HOWEVER, later in the process, this ended up causing me no end of trouble.  Specifically, when I later tried to link in the Lua DLL, I started getting run-time errors:  &#8220;&#8221;The application has failed to start because MSVCR80.dll was not found.&#8221;  I then did some cursory searching around the internet and found that I was not alone.  There are <a href="http://www.itwriting.com/blog/?postid=261">several</a> <a href="http://www.grimes.demon.co.uk/workshops/fusWSThirteen.htm">articles</a> <a href="http://msdn2.microsoft.com/en-us/library/ms235299(VS.80).aspx">about</a> <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=23261">this</a>.  I tried several solutions regarding the DLL manifest, but nothing seemed to solve my problem.  One day I&#8217;ll really have to learn about DLL manifests and assemblies, but for now I just wanted to get this to work like it used to with VC7 and VC6.  At one point, I even got so annoyed as to contemplate building KDE and KDevelop on Windows so I could use the same environment on Linux and Windows &#8211; but then I got a-hold of myself.</p>
<p>Ultimately, I downloaded <a href="http://www.mingw.org/">MinGW</a> and built the Lua libraries using the makefile:</p>
<ul>
<li>Ensure the MinGW executables are in your path.  Either copy all .exe files to an executable path or add to your PATH environment variable in Windows (right-click My Computer > Properties > Advanced > Environment Variables > System Variables)</li>
<li>In a new command prompt, cd to c:\lua-5.1.2\</li>
<li>mingw32-make mingw</li>
<li>Confirm the library files were built:  lua51.lib will be sitting in c:\lua-5.1.2\src\ and lua51.dll will be sitting in c:\lua-5.1.2\mingw\</li>
</ul>
<p>These build instructions are also in the INSTALL file if you need further reference.</p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
</div>
<div id="DownloadLuabridge">
<h3>Downloading Luabridge</h3>
<p>Now that Lua is built, we&#8217;re going to install Luabridge, which allows us to cleanly talk between C++ and Lua.  Go download the latest (0.2) from <a href="http://sourceforge.net/project/showfiles.php?group_id=190772">here</a>.  Then unzip the package (I used c:\ so it unrolled into c:\luabridge-0.2\).</p>
</div>
<div id="BuildLuabridge">
<h3>Building Luabridge</h3>
<p>We&#8217;re getting close now.  Next, we&#8217;re going to build Luabridge.  There are VC7 (.NET 2003) and VC8 (.NET 2005) projects included in the zip as well as the standard Makefile.  I used the VC8 project, of course.</p>
<p>Open up the solution file and update both projects:  Add c:\lua-5.1.2\etc\ and c:\lua-5.1.2\src\ to the include directories.  Add c:\lua-5.1.2\src\ to the library paths.  Add lua51.lib as a library dependency.</p>
<p>Now build the Luabridge project.  You should see a libluabridge.lib (or libluabridged.lib for Debug) file get created in c:\luabridge-0.2\lib\.</p>
<p>To run the test project in the Luabridge solution, you will have to copy over the lua51.dll from c:\lua-5.1.2\src\ to the &#8220;test&#8221; project&#8217;s executable path.  Now go to a command prompt, change directory to c:\luabridge-0.2 and type src\testd.  You should see a &#8220;All tests succeeded&#8221; message.  This proves that we&#8217;ve built Lua and Luabridge successfully.</p>
</div>
<div id="AddLuaAndLuabridge">
<h3>Adding Lua and Luabridge To Your Game</h3>
<p>Now is the last step &#8211; we&#8217;re going to integrate Lua with an existing C++ game or project using Luabridge.  Since you&#8217;re now an expert on Visual Studio project configuration I&#8217;ll just breeze over the steps:</p>
<ul>
<li>Add the Lua and Luabridge header files into your include paths</li>
<li>Add the library path to the Lua and Luabridge libraries</li>
<li>Add lua51.lib and libluabridge.lib (libluabridged.lib for Debug) to your dependencies</li>
<li>Copy the lua51.dll into your executable path (Luabridge does not require a DLL as it really only uses C++ template metaprogramming to achieve its ends)</li>
</ul>
<p>An interesting note on Luabridge:  In order to pass C++ objects to Lua using Luabridge, you can&#8217;t just send Foo* as an argument or a return value to a function.  The reason is that the object pointed to by your Foo pointer might be deleted at some point in C++ land &#8211; yet Lua-land won&#8217;t know that and when it tries to access the object, it will cause problems (crashes).  To help circumvent this, Luabridge requires that pointers to C++ objects be wrapped in a smart pointer, specifically a <i>shared_ptr</i> templated object.  This ensures that as long as someone still has a reference to this pointer, the object will not be deleted.</p>
<p>You can use the minimal shared_ptr that comes with Luabridge, or you can use a different shared_ptr template that conforms to the Boost shared_ptr template.  I recommend you use Boost&#8217;s version if you have the guts to download it, because it allows things like default creation of shared_ptr&#8217;s without assigning values (useful if you want to have a fixed array of objects, for instance).  Here&#8217;s how I set up my C++ project to use Boost&#8217;s shared_ptr with Luabridge:</p>
<p><code></p>
<p>&#160;&#160;&#160;&#160;#include &#60;boost/shared_ptr.hpp></p>
<p>&#160;&#160;&#160;&#160;using boost::shared_ptr;</p>
<p>&#160;&#160;&#160;&#160;#define USE_OTHER_SHARED_PTR</p>
<p>&#160;&#160;&#160;&#160;#include &#60;luabridge.hpp></p>
<p></code></p>
</div>
<p>I&#8217;ll get into how you can actually code with Luabridge in a later blog post &#8211; once you&#8217;ve got it all linked in, it&#8217;s really not that hard.</p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2007/11/16/bridging-the-gap-cleanly-setting-up-luabridge/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting To Know C++ Next: Filesystem</title>
		<link>http://www.codedread.com/blog/archives/2007/07/12/getting-to-know-c-next-filesystem/</link>
		<comments>http://www.codedread.com/blog/archives/2007/07/12/getting-to-know-c-next-filesystem/#comments</comments>
		<pubDate>Thu, 12 Jul 2007 16:28:11 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.codedread.com/archives/2007/07/12/getting-to-know-c-next-filesystem/</guid>
		<description><![CDATA[The next version of C++ is going to include some nice, shiny new libraries in its standard namespace. These libraries will really beef up the things that C++ developers want to be able to do in a cross-platform fashion. It&#8217;s not clear to me what will happen to the libraries in TR2. I hope things [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://en.wikipedia.org/wiki/C%2B%2B0x">next version of C++</a> is going to include some nice, shiny new libraries in its standard namespace.  These libraries will really beef up the things that C++ developers want to be able to do in a cross-platform fashion.  It&#8217;s not clear to me what will happen to the libraries in <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1810.html" title="Technical Report 2">TR2</a>. I hope things like accessing the bloody file system will make its way into the next version of C++.  Here&#8217;s a quicky look at how one might do that using Boost.Filesystem.  <span id="more-387"></span></p>
<p>I&#8217;ve really only started using <a href="http://www.boost.org/libs/filesystem/doc/index.htm">Boost.Filesystem</a> very recently to replace some platform-specific code that accessed the file system so that I could port my code over to <a href="http://www.opensuse.org/">OpenSUSE</a> (Linux).  That change was pretty much the only thing I had to do because the rest of the program relies on <a href="http://www.libsdl.org/" title="Simple DirectMedia Library">SDL</a> which is already cross-platform.</p>
<p>The code I was using was originally ported from DOS to Windows and used the functions <a href="http://msdn2.microsoft.com/en-us/library/zyzxfzac(VS.71).aspx">_findfirst()</a>, _findnext() to access a directory contents, iterate through each file and find all files ending in a specific extension.  A pretty common operation really, so I thought I&#8217;d post this as an example to get people looking at Boost.Filesystem:</p>
<div class="code">
<pre>
#include &#60;string>
#include &#60;vector>
#include &#60;boost/filesystem.hpp>
using namespace boost::filesystem;
using std::string;
using std::vector;

  <span style="color:green">// get all files ending in .tsg</span>
  vector&#60; string > filenames;
  path dir_path("data/savegame/");
  directory_iterator end_it; <span style="color:green">// [1]</span>
  <span style="color:green">// loop through each file in the directory</span>
  for(directory_iterator it(dir_path); it != end_it; ++it) {
    <span style="color:green">// if it's not a directory and its extension is .tsg [2]</span>
    if( !is_directory(it->status()) &#038;&#038; extension(it->path()) == ".tsg" ) {
      <span style="color:green">// store filename for later use</span>
      filenames.push_back( it->path().string() );
    }
  }
</pre>
</div>
<p>Now your filenames vector contains all the filenames in the directory &#8220;data/savegame/&#8221; that had an extension &#8220;.tsg&#8221;.  Some notes on this example:</p>
<ol>
<li>By default, a directory_iterator usefully points to &#8220;past the end&#8221;</li>
<li>Extensions are case-sensitive on Linux</li>
</ol>
<p>So basically, a <i>path</i> is pretty much what you&#8217;d expect:  a location in the filesystem which can either be a directory or a file.  You can get the full string representation by calling the member method string().  A <i>directory_iterator</i> allows you to iterate through all items in the path.  There are some convenience functions like <i>extension()</i> and <i>basename()</i>.  The <i>leaf()</i> member function of a <i>path</i> returns a string holding the last file or directory name in the path object if you ever need that.</p>
<div class="ads"><object type="text/html" width="475" height="70" data="http://www.codedread.com/gads.php"></object></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2007/07/12/getting-to-know-c-next-filesystem/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Feed Sweep</title>
		<link>http://www.codedread.com/blog/archives/2007/06/29/feed-sweep/</link>
		<comments>http://www.codedread.com/blog/archives/2007/06/29/feed-sweep/#comments</comments>
		<pubDate>Fri, 29 Jun 2007 14:47:09 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[QuickLinks]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.codedread.com/archives/2007/06/29/feed-sweep/</guid>
		<description><![CDATA[To supplement all the iPhone buzz, I thought I&#8217;d throw up a few totally unrelated links/stories I found in my feed aggregator to make you a well-rounded geek. Weaning Off The Microsoft Juice As a hobby, I develop in Linux these days using KDevelop. For Windows, I still use Microsoft&#8217;s Visual C++ because Developer&#8217;s Studio [...]]]></description>
			<content:encoded><![CDATA[<p>To supplement all the iPhone buzz, I thought I&#8217;d throw up a few totally unrelated links/stories I found in my feed aggregator to make you a well-rounded geek.  <span id="more-384"></span></p>
<h3>Weaning Off The Microsoft Juice</h3>
<p>As a hobby, I develop in Linux these days using <a href="http://www.kdevelop.org/">KDevelop</a>.  For Windows, I still use Microsoft&#8217;s Visual C++ because Developer&#8217;s Studio is still one of the best IDEs I&#8217;ve come across for Windows.  <a href="http://cdtdoug.blogspot.com/2007/06/introducing-cdt-for-windows.html">Doug just released</a> a self-contained <a href="http://www.eclipse.org/cdt/">Eclipse CDT</a> plus <a href="http://en.wikipedia.org/wiki/Mingw">MinGW</a> compiler.  If that doesn&#8217;t mean anything to you, so be it &#8211; but it&#8217;s something I&#8217;m excited about.  Looks like he also <a href="http://cdtdoug.blogspot.com/2007/06/dont-try-this-at-home.html">acknowledges</a> that Eclipse CDT can be slow/sluggish so probably still lots of work to do.  I should get around to testing this one day.  If you code C/C++ in Windows &#8211; what do you use?</p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
<h3>Organizize Your Google Docs</h3>
<p><a href="http://docs.google.com">Google Docs</a> updates allow you to now organize your documents into online folders &#8211; and the web browser inches a little closer to a platform that replaces things you do with your operating system&#8230;</p>
<h3>Google Maps Snaps</h3>
<p>Via <a href="http://www.downloadsquad.com/2007/06/29/plan-a-trip-and-a-detour-with-google-maps/">Download Squad</a>, <a href="http://maps.google.com/">Google Maps</a> has added an awesome new feature.  Now if you don&#8217;t like the directions that you get, you can click and drag to change your route.  The blue directional route snaps to the streets that you will have to take.  Pretty impressive stuff (though I did notice that if you click and drag enough it can get pretty confused &#8211; I&#8217;m sure they&#8217;ll refine their snapping/merging algorithm).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2007/06/29/feed-sweep/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Next C++</title>
		<link>http://www.codedread.com/blog/archives/2006/01/03/the-next-c/</link>
		<comments>http://www.codedread.com/blog/archives/2006/01/03/the-next-c/#comments</comments>
		<pubDate>Tue, 03 Jan 2006 16:46:02 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.codedread.com/?p=199</guid>
		<description><![CDATA[Via Slashdot. Bjarne Stroustroup, the &#8220;designer and original implementor&#8221; of the C++ programming language, gives a look forward at the features most likely to be included in the next version of C++, titled C++0x (possibly one of the worst symbol ever for a programming language version). I was surprised to learn from this article that [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://it.slashdot.org/article.pl?sid=06/01/03/0351202&#038;from=rss">Via Slashdot</a>.  Bjarne Stroustroup, the &#8220;designer and original implementor&#8221; of the C++ programming language, gives a <a href="http://www.artima.com/cppsource/cpp0x.html" title="Bjarne Stroustroup's A Brief Look At C++0x">look forward</a> at the features most likely to be included in the next version of C++, titled C++0x (possibly one of the worst symbol ever for a programming language version).  <span id="more-199"></span></p>
<p><script type="text/javascript" src="http://www.codedread.com/googleads.js"></script><br />
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></p>
<p>I was surprised to learn from this article that the next version of C++ won&#8217;t likely be ready until 2009.  They&#8217;ve been batting around ideas for this version for awhile (the last version of C++ was C++98).  On one hand it&#8217;s great that developers and compiler/<span class="definition" title="Integrated Development Environment">IDE</span> implementors will be able to keep up with the new versions of the language.  On the other hand, it seems to cast a negative shadow on the slow-moving process when compared to other technologies (like web technologies for instance).  After all, a lot happens in 3 years (let alone 11 years) in the technology space.</p>
<p>According to Stroustroup, the committee is made of up volunteers who all have &#8220;day jobs&#8221;, so that explains the pace to some degree.  Anyway, I somehow get the feeling that the process is moving at a deliberate pace to give time for the market to absorb changes from the last version to see what worked, what didn&#8217;t and what needs are out there.  I don&#8217;t think the C++ committee feels they need to compete with other technologies since C++ is so well-established in its <span class="definition" title="Is that an oxymoron?">very wide niche</span>.  This isn&#8217;t to say that C++ doesn&#8217;t need an upgrade &#8211; I agree with Stroustroup, the overall syntax for generic programming in C++ currently sucks (not a big surprise since, if I understand things correctly, generics were thrown in almost as an after-thought in the original C++ design).</p>
<p>Anyway, the underlying goals of committee are noble:</p>
<blockquote><ul>
<li>Provide stability and compatibility (with C++98, and, if possible, with C)</li>
<li>Prefer standard library facilities to language extensions</li>
<li>Make only changes that change the way people think</li>
<li>Prefer generality to specialization</li>
<li>Support both experts and novices</li>
<li>Increase type safety (by providing safe alternatives to currently unsafe facilities)</li>
<li>Improve performance and ability to work directly with hardware</li>
<li>Fit into the real world</li>
</ul>
</blockquote>
<p>Stroustroup doesn&#8217;t give away much, since nothing is absolutely firm yet.  But here&#8217;s an example of some code that would align with some of the things he talks about:</p>
<p>Proposed C++0x code:</p>
<div class="code">
std::vector&#60;double&#62; vec = { 2.4, 1.1, 9.9 };<br />
for( auto it = vec.begin(); it != vec.end(); ++it) { &#8230; }
</div>
<p>Equivalent C++89 code:</p>
<div class="code">
std::vector&#60;double&#62; vec;<br />
vec.push_back(2.4);<br />
vec.push_back(1.1);<br />
vec.push_back(9.9);<br />
for( std::vector&#60;double&#62;::iterator it = vec.begin(); it != vec.end(); ++it) { &#8230; }
</div>
<p>I know which version I prefer!</p>
<p>The idea of the &#8220;auto&#8221; is great &#8211; it means &#8220;figure out which type I need&#8221;.  This is fantastic for iterators like the above example &#8211; now if I change my underlying container to a std::list, I don&#8217;t need to change the iterator type (or write a typedef for it), the compiler will pick up the change automatically.  Of course you could use the C++98 version if you want to automatically typecast the iterator to some other type but clearly the &#8220;auto&#8221; idea makes great sense.  Anyway, the idea is to eliminate all that unnecessary typing: Why should I have to do all that typing when vec.begin() returns a <em>std::vector&#60;double&#62;::iterator</em> in the first place?  I welcome this addition to the language but it may make some programmers lazier in the long run.  I can just see people putting &#8220;auto&#8221; every place instead of looking up the return types of functions and then getting into trouble with casting operations later &#8211; hopefully compiler warnings will keep us in line.</p>
<p>The ability to initialize a user-defined container via a list is less important to me, but it is appreciated since it puts user-defined containers almost on par with arrays and structs.</p>
<p>Stroustroup also mentions the idea of <em>concepts</em> which he describes as a &#8220;type of a type&#8221;.  In this facility, you specify within a template declaration what properties a template argument must have in order to be properly used within a template.  This is used today, I remember Alexandrescu&#8217;s <em>Loki</em> library as described in &#8220;<a href="http://www.amazon.com/exec/obidos/redirect?link_code=as2&#038;path=ASIN/0201704315&#038;tag=codedread-20&#038;camp=1789&#038;creative=9325">Modern C++ Design</a><img src="http://www.assoc-amazon.com/e/ir?t=codedread-20&#038;l=as2&#038;o=1&#038;a=0201704315" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />&#8220;, which uses this heavily.  But if I understand Stroustroup here, the proposed <em>where</em> clause would allow for less cryptic compiler error handling up-front and to disambiguate &#8220;between templates taking the same number of arguments&#8221;.  I&#8217;ll be interested to see this one when it&#8217;s fully baked because, as a C++ geek, I&#8217;m obliged to be a fan of generic programming <img src='http://www.codedread.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Stroustroup also mentions many of the libraries he would like to see in the next version of the Standard Template Library (STL).  I&#8217;d personally like to see all of the following standardized now (that way I wouldn&#8217;t have to worry about including the correct header files in my projects):</p>
<ul>
<li><a href="http://www.boost.org/libs/filesystem/doc/index.htm" title="Boost.Filesystem C++ Library">Boost.Filesystem</a> &#8211; for dealing with directories and files</li>
<li><a href="http://www.boost.org/libs/bind/bind.html" title="Boost.bind C++ Library">Boost.bind</a>, <a href="http://www.boost.org/libs/bind/mem_fn.html" title="Boost.mem_fn C++ Library">Boost.mem_fn</a>, <a href="http://www.boost.org/doc/html/function.html" title="Boost.Function C++ Library">Boost.Function</a> &#8211; for function binding, callbacks</li>
<li>
</li>
<li><a href="http://www.boost.org/libs/thread/doc/index.html" title="Boost.Thread C++ Library">Boost.Thread</a> &#8211; for multi-threaded programming</li>
<li><a href="http://www.boost.org/libs/spirit/index.html" title="Boost.Spirit C++ Library">Boost.Spirit</a> &#8211; for inline parsing of EBNF grammars</li>
</ul>
<p>You could make arguments that Filesystem and Spirit are outside the core language principles and should stand as separate libraries, but this is my pet list after all so <em>nyah</em>!</p>
<p><script type="text/javascript" src="http://www.codedread.com/googleads.js"></script><br />
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2006/01/03/the-next-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SDL in Games: Old School</title>
		<link>http://www.codedread.com/blog/archives/2005/08/24/sdl-in-games-old-school/</link>
		<comments>http://www.codedread.com/blog/archives/2005/08/24/sdl-in-games-old-school/#comments</comments>
		<pubDate>Wed, 24 Aug 2005 21:32:13 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[SDL]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.codedread.com/?p=141</guid>
		<description><![CDATA[Read Part One if you haven&#8217;t. So with a little SDL graphics knowledge under my belt, I decided that I would set out to actually implement the old BGI library using SDL. That is, I wanted to use the same game code for Ten Nights but instead of linking to obsolete Borland libraries that would [...]]]></description>
			<content:encoded><![CDATA[<p>Read <a href="http://blog.codedread.com/archives/2005/08/23/sdl-in-games-introduction/">Part One</a> if you haven&#8217;t.  So with a little <abbr title="Simple DirectMedia Layer">SDL</abbr> graphics knowledge under my belt, I decided that I would set out to actually implement the old BGI library using SDL.  That is, I wanted to use the same game code for Ten Nights but instead of linking to obsolete Borland libraries that would no longer work in Windows-based system, I wanted to link to my own library that would look the same (from the game&#8217;s perspective), yet work in Windows via SDL.  <span id="more-141"></span></p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
<p>I decided to start by porting another simpler game written by Sinasac (&#8220;Caverns of Xaskazien&#8221;).  The original codebase of &#8220;Caverns&#8221; was C and clocked in under 5000 lines.  Once I set up a C++ project, linked in a stub of the BOSS library, corrected various compiler errors and warnings that were no longer &#8220;correct&#8221; (the Borland compiler strictness of the early nineties were pretty lax compared to today), the game actually compiled and ran.  Then I started filling in the BGI functions that I needed by writing them using C++ and SDL.   You can see the early development timeline of BOSS <a href="http://www.codedread.com/code/BOSS/docs/history.html">here</a>. I wrote the basic workable BOSS library and ported the &#8220;Caverns&#8221; code in 5 days and handed the &#8220;Caverns&#8221; code back to Sinasac two days before my wife gave birth to our two wonderful baby boys.  Yes, I know I should have been rubbing her feet that whole time&#8230;</p>
<p>Note that I only wrote the BOSS functions that the game needed, no more.  My goal in the BOSS library was only for porting the existing games, not for being &#8220;feature complete&#8221;.  I think this was really the start of my newer philosophy on development:  Set smaller goals and march towards them, don&#8217;t get distracted and don&#8217;t try to engineer the ultimate generic solution.  This eventually morphed into:  Do incremental steps to achieve what you want, while always providing a fully functional app (something akin to the &#8220;Small Releases&#8221; goal in <a href="http://www.jera.com/techinfo/xpfaq.html#xppractices">eXtreme Programming</a> methodology).  The focus on delivering builds that are always fully functional keeps my goals smaller and more incremental, but gives me a better chance of actually achieving them, given my limited free time to work on this stuff.</p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
<p>Anyway, the success of the initial stages of BOSS got me working on expanding it to include old-school keyboard handling like getch(), bioskey(), kbhit() and to implement a sound subsystem that originally came out of &#8220;The Black Art of Game Programming&#8221; (Andre Lemothe).  All of it done in SDL with little problems (implementing bioskey() and getch() proved to be the most challenging).  With all these things packed into BOSS, it was fairly usable as a &#8220;guts replacement&#8221; for the old-school C libraries that the games used and it was fairly straightforward to set up &#8220;Ten Nights&#8221; to use BOSS.</p>
<p>I&#8217;m done with Boss now.  If someone wants to finish BOSS up, I would open source the project, but I can&#8217;t imagine the call for such a thing would be very strong.  Borland&#8217;s BGI libraries are already more than a decade obsolete.</p>
<p>You see, the usefulness of BOSS is only for porting old applications that relied on these ancient libraries, it is hardly useful for more modern game programming.  For that, it makes sense to use SDL directly for both maximum flexibility and speed.</p>
<p>With that in mind, I started out restructuring &#8220;Ten Nights&#8221; to use SDL directly, moving functionality piece-by-piece to use SDL directly (instead of the BOSS wraparound).</p>
<p>Then&#8230;. well, my kids were born&#8230; so the pace slowed down quite a bit&#8230; (hear the crickets chirping?)</p>
<p>More on SDL development for games in Part Three.</p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2005/08/24/sdl-in-games-old-school/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SDL in Games: Introduction</title>
		<link>http://www.codedread.com/blog/archives/2005/08/23/sdl-in-games-introduction/</link>
		<comments>http://www.codedread.com/blog/archives/2005/08/23/sdl-in-games-introduction/#comments</comments>
		<pubDate>Tue, 23 Aug 2005 16:18:27 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[SDL]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://blog.codedread.com/?p=142</guid>
		<description><![CDATA[Since I spent the last 6 months or so getting geeked about web development, SVG, JavaScript, Ajax and XML. I think it&#8217;s about time I shift my focus back for a little while on some standard C++ game development for the desktop. I find that my mind naturally migrates every so often (usually 6 months) [...]]]></description>
			<content:encoded><![CDATA[<p>Since I spent the last 6 months or so getting geeked about web development, <abbr title="Scalable Vector Graphics">SVG</abbr>, JavaScript, Ajax and XML.  I think it&#8217;s about time I shift my focus back for a little while on some standard C++ game development for the desktop.  I find that my mind naturally migrates every so often (usually 6 months) between interests/hobbies that I have.  It&#8217;s like my brain is saying that it needs a breather from obsessing about one thing so it&#8217;s time to obsess on another.  Mild <abbr title="Obsessive Compulsive Disorder">OCD</abbr> anyone?  <span id="more-142"></span></p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
<p>So for the past week, I&#8217;ve been hacking away at the code for <a href="http://www.codedread.com/games.php#TNO">Ten Nights of Killing and Mayhem</a> when I have some free time.  Development is also being spurred on by the fact that Jeff Sinasac has some time to generate some new sounds and graphics for the game.  Fresh resources are always good incentive to get more work done.</p>
<p>&#8220;Ten Nights of Killing and Mayhem&#8221; was originally a board game that Sinasac and I designed (with the invaluable help of a few others) in high school (1991).  In retrospect, the subject matter is hardly politically correct, maybe even disturbing, but it was a fun creative outlet for us during a time when we needed it.  About a year later (1992-ish), Sinasac wrote &#8220;Ten Nights&#8221; as a DOS-based game.  Then maybe a year or two after that he rewrote it to use enhanced graphics/sound (though still DOS-based).  By this time the game resembled a primitive top-down <a href="http://www.xcomufo.com/gameinfo.html">X-Com</a> in its gameplay and approach.</p>
<p>The DOS-based game used the Borland graphics libraries (<a href="http://www.cs.colorado.edu/~main/bgi/doc/">Borland Graphics Interface</a> or BGI), but since the migration from DOS-based systems to Windows-based systems in the mid-nineties, such graphics libraries are long past their point of usefulness.  With the advent of modern media technologies, something new was needed.</p>
<p>Porting directly to <a href="http://www.microsoft.com/windows/directx/default.aspx">DirectX</a> was one option, but DirectX is heavily <a href="http://www.microsoft.com/com/default.mspx">COM</a>-based and would have required drastic rewrites of a non-trivial codebase.  My goal was to get &#8220;Ten Nights&#8221; up and running as quick as possible in Windows (and then later enhance it).</p>
<p><a href="http://www.libsdl.org/index.php">Simple DirectMedia Layer</a> (SDL) is similar to DirectX in that it providing access to graphics, keyboard/mouse event handling, audio, etc for games.  Yet SDL is a cross-platform library and is (therefore) not dependent upon the user worrying about COM, Window handles, display context, and the like.  In essence, you can disengage from learning heavy platform-specific code and, once you know a little SDL, just work on your game.  You also have the side benefit of easing ports to other platforms.</p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
<p>Actually SDL&#8217;s approach to 2D graphics is fairly minimal.  It allows you to configure your video settings (resolution, colour depth), load images (Windows BMP only), obtain pointers to surfaces that represent image data (both onscreen and in-memory), and perform <abbr title="Block LInear Transfers">blits</abbr> to the screen.  The blits can be standard copies, colour-keyed copies (to provide simple transparencies or sprites) or more complex alpha-blended blits (to provide opacity and blending effects).  There are a couple other lesser-used functions in SDL, but from a graphics perspective that&#8217;s about it.</p>
<p>In some respects, since SDL needs to be cross-platform, it (unfortunately) needs to provide a &#8220;least-common denominator&#8221; approach for basic graphics support.  For instance, SDL does not even provide a function to get or set an individual pixel colour, you actually have to write your own (or use the code provided in the SDL documentation <a href="http://www.libsdl.org/intro/usingvideo.html">here</a>).  However, it makes up for this sparseness by providing hardware accelerated support on platforms that can do this (for example, SDL uses DirectDraw on Windows platforms for fast hardware support on video cards that support this).  SDL also has some good extension libraries you can add onto that provide you with richer functionality (more on these in later entries).</p>
<p>In addition, SDL provides the benefit of allowing you to handle events (keyboard, mouse, timer, joysticks) and audio in a cross-platform manner, which is a huge benefit if you&#8217;re thinking of writing games once that can run everywhere.  You can pick and choose the components that you need from SDL and there&#8217;s not a lot of complicated &#8220;initialization&#8221; steps that need to happen before you can do something useful.</p>
<p>SDL does not provide support for 3D graphics, but it does integrate nicely with <a href="http://www.opengl.org/">OpenGL</a>.  For example, you could use SDL to handle all your window initialization, event-handling, audio and then use OpenGL for your 3D graphics.</p>
<p>SDL is pretty easy to pick up since there&#8217;s not a lot of complicated things to learn.  Everything is straight-forward C-style API calls and you&#8217;ve only got to learn about a few structs (the most important of which is SDL_Surface) before you can start doing something useful.</p>
<p>Anyway, weighing the pros and cons of SDL, early March 2004 I decided to learn about SDL and work towards porting the old games to SDL.   Was it spurred on by my anxiety related to my wife being due with twins that month?  Was this my last-ditch attempt to reclaim my geek programming life and relive my high-school glory days before I became a family man?  More coming in <a href="http://blog.codedread.com/archives/2005/08/24/sdl-in-games-old-school/">Part Two</a>&#8230;</p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2005/08/23/sdl-in-games-introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing Copyable C++ Classes</title>
		<link>http://www.codedread.com/blog/archives/2005/03/23/writing-copyable-c-classes/</link>
		<comments>http://www.codedread.com/blog/archives/2005/03/23/writing-copyable-c-classes/#comments</comments>
		<pubDate>Wed, 23 Mar 2005 17:59:18 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">/?p=72</guid>
		<description><![CDATA[I thought I&#8217;d jot down some notes on what I do when designing new classes in C++ to be copyable. I&#8217;d be curious to get some feedback as I&#8217;m not sure what the C++ community at large does&#8230; Anyway, when creating a new class where objects of that class need to be copyable, the first [...]]]></description>
			<content:encoded><![CDATA[<p>I thought I&#8217;d jot down some notes on what I do when designing new classes in C++ to be copyable.  I&#8217;d be curious to get some feedback as I&#8217;m not sure what the C++ community at large does&#8230;  <span id="more-72"></span></p>
<p>Anyway, when creating a new class where objects of that class need to be copyable, the first thing I ask myself is:</p>
<h2>1. Is the new class a Plain Old Data type?</h2>
<p>My definition of a Plain Old Data type (&#8220;POD&#8221;) is one that simply includes a fixed amount of publicly accessible data.  This rules out anything that would include a member function, anything that has any dynamic memory allocation aspects and anything that would have protected/private data members.</p>
<p>If so, designing the class can be quite simple.  I don&#8217;t need to worry about:</p>
<ul>
<li>copy constructors</li>
<li>assignment operators</li>
<li>destructors</li>
</ul>
<p><code><br />
class DatabaseRow {<br />
public:<br />
&#160;&#160;unsigned int Id;<br />
&#160;&#160;unsigned short Year;<br />
&#160;&#160;char FilmName[255];<br />
&#160;&#160;<br />
&#160;&#160;DatabaseRow(unsigned int _id, unsigned short _year, const char* _filmName)<br />
&#160;&#160;&#160;&#160;: Id(_id), Year(_year)<br />
&#160;&#160;{<br />
&#160;&#160;&#160;&#160;FilmName[0] = 0;<br />
&#160;&#160;&#160;&#160;if(_filmName) {<br />
&#160;&#160;&#160;&#160;&#160;&#160;if(strlen(_filmName) &#60; 255) {<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;strcpy(FilmName, _filmName);<br />
&#160;&#160;&#160;&#160;&#160;&#160;}<br />
&#160;&#160;&#160;&#160;&#160;&#160;else {<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;memcpy((void*)FilmName, (void*)_filmName, sizeof(char) * 254);<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;FilmName[254]=0;<br />
&#160;&#160;&#160;&#160;&#160;&#160;}<br />
&#160;&#160;&#160;&#160;} // if(_filmName)<br />
&#160;&#160;} // end constructor<br />
};<br />
</code></p>
<p>The compiler will supply hidden default (no-argument) constructor and a copy constructor for the above class which will work fine (since all data members are fixed length, no dynamic memory allocation takes place).  There is also no need for an explicit destructor since all data members are automatically destroyed.</p>
<h2>2. If not a POD, will I really need to copy objects of this class?</h2>
<p>Sometimes it&#8217;s obvious when you will need to do copies, other times it&#8217;s not so obvious but it becomes convenient.  For instance, if I want to avoid having to allocate and (remember to) de-allocate memory at runtime for an object I sometimes want to make it part of a class.  i.e.:</p>
<p><code><br />
class C1 { ... }<br />
&#160;&#160;<br />
class C2 {<br />
&#160;&#160;<br />
&#160;&#160;C1 objectOfTypeC1;<br />
};<br />
</code></p>
<p>In the above, I want C2 to contain an object of type C1 when C2 is instantiated.  I don&#8217;t want to have C2 contain a pointer to C1 and then have to allocate a C1 inside C2&#8242;s constructor then remember to de-allocate a C1 when C2 is destroyed (lest I cause a memory leak).  Any time I can avoid having to keep track of a pointer, I usually try to (though smart pointers can ease this task and static allocation really has become just a preference of mine).</p>
<p>Another scenario is when you have an array of objects:</p>
<p><code><br />
class C3 {<br />
&#160;&#160;C1 anArrayOfC1s[2085];<br />
};<br />
</code></p>
<p>Now an object of type C3 contains an array of 2085 C1 objects which are allocated when the object of type C3 is instantiated.</p>
<p>One problem with doing the above is that the C1 objects are statically created when the enclosing class is created using a default (no-argument) constructor.  Often-times objects of the contained class (C1) cannot be constructed meaningfully at the time of the enclosing class&#8217; (C2) instantiation, especially if it&#8217;s during program startup as opposed to at run-time.</p>
<p>Ultimately, this means you cannot specify any details about the individual C1 objects and often need to &#8220;initialize&#8221; those objects at some later state (a messy approach) or &#8220;reconstruct&#8221; those objects and copy them back to data members of the enclosing class.</p>
<p>For scenarios like this, it means I will supply the following:</p>
<ul>
<li>A copy constructor</li>
<li>An assignment operator</li>
</ul>
<p>I usually throw in a default, no-argument constructor and a destructor at this point too.  Here&#8217;s my standard approach for this, which I&#8217;ve been using for a couple years now:</p>
<p><code><br />
class DataBaseTable {<br />
private:<br />
&#160;&#160;string Name;<br />
&#160;&#160;vector&#60;DatabaseRow&#62; Rows;<br />
protected:<br />
&#160;&#160;bool deepcopy(const DataBaseTable&#038; rhs) {<br />
&#160;&#160;&#160;&#160;bool bResult = false;<br />
&#160;&#160;&#160;&#160;if(&#038;rhs != this) {<br />
&#160;&#160;&#160;&#160;&#160;&#160;this-&#62;Name = rhs.Name;<br />
&#160;&#160;&#160;&#160;&#160;&#160;vector&#60;DatabaseRow&#62;::iterator it = rhs.Rows.begin();<br />
&#160;&#160;&#160;&#160;&#160;&#160;while(it != rhs.Rows.end()) {<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;this-&#62;Rows.push_back(*it);<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;++it;<br />
&#160;&#160;&#160;&#160;&#160;&#160;}<br />
&#160;&#160;&#160;&#160;&#160;&#160;bResult = true;<br />
&#160;&#160;&#160;&#160;}<br />
&#160;&#160;&#160;&#160;return bResult;<br />
&#160;&#160;}<br />
public:<br />
&#160;&#160;DataBaseTable() : { Name[0] = 0; }<br />
&#160;&#160;DataBaseTable(const DataBaseTable&#038; rhs) { deepcopy(rhs); }<br />
&#160;&#160;DataBaseTable&#038; operator=(const DataBaseTable&#038; rhs) { deepcopy(rhs); return *this; }<br />
&#160;&#160;<br />
&#160;&#160;const DatabaseRow&#038; getRow() const { ... }<br />
};<br />
</code></p>
<p>We supply a member function called &#8220;deepcopy&#8221; that ensures all data members are properly copied from &#8220;rhs&#8221; to &#8220;this&#8221; in a proper fashion.</p>
<p>The reason I return bool from this function is so that with a hierarchy of classes (all of which must be copyable), I can reuse the base class&#8217; deepcopy as a starting point.  For example:</p>
<p><code><br />
class Base {<br />
private:<br />
&#160;&#160;int arrayLength;<br />
&#160;&#160;int* someArray;<br />
protected:<br />
&#160;&#160;bool deepcopy(const Base&#038; rhs) {<br />
&#160;&#160;&#160;&#160;bool bResult = false;<br />
&#160;&#160;&#160;&#160;if(&#038;rhs != this) {<br />
&#160;&#160;&#160;&#160;&#160;&#160;this-&#62;arrayLength = rhs.arrayLength;<br />
&#160;&#160;&#160;&#160;&#160;&#160;this-&#62;someArray = new int[this-&#62;arrayLength];<br />
&#160;&#160;&#160;&#160;&#160;&#160;for(int ind = 0; ind &#60; this-&#62;arrayLength; ++ind) { this-&#62;someArray[ind] = rhs.someArray[ind]; }<br />
&#160;&#160;&#160;&#160;&#160;&#160;bResult = true;<br />
&#160;&#160;&#160;&#160;}<br />
&#160;&#160;&#160;&#160;return bResult;<br />
&#160;&#160;}<br />
&#160;&#160;// etc...<br />
};<br />
</code></p>
<p>Now in a derived class, deep copying can be extended like so:</p>
<p><code><br />
class Derived : public Base {<br />
public:<br />
&#160;&#160;int someOtherValue;<br />
protected:<br />
&#160;&#160;bool deepcopy(const Derived&#038; rhs) {<br />
&#160;&#160;&#160;&#160;bool bResult = Base::deepcopy(rhs);<br />
&#160;&#160;&#160;&#160;if(bResult) {<br />
&#160;&#160;&#160;&#160;&#160;&#160;this-&#62;someOtherValue = rhs.someOtherValue;<br />
&#160;&#160;&#160;&#160;}<br />
&#160;&#160;&#160;&#160;return bResult;<br />
&#160;&#160;}<br />
&#160;&#160;// etc...<br />
};<br />
</code></p>
<p>Of course the drawback of this technique is that every class in your hierarchy has to have a &#8220;deepcopy&#8221; method.  However, it does save time when writing the assignment operator and copy constructors, since they rely on the deepcopy method and their function bodies become completely trivial.</p>
<h2>3. Should copying an object cause any side effects to the original object?</h2>
<p>This is a little trickier topic, since while the answer seems very obvious at first I&#8217;ve come across a scenario where it wasn&#8217;t the case.  My example was when an object had sole responsibility or control over an external resource and I needed to transfer ownership to the new copy and remove ownership from the old copy.  This means that copying an object has a side effect to the copied object on the right-hand-side of the assignment operator.</p>
<p>In this case, you will have to remove the keyword &#8220;const&#8221; from the deepcopy, copy constructor and assignment operator methods.  You should also explicitly document what is going on when a copy is made as a client/user will assume (and rightfully so) that performing a copy will leave the right-hand-side copy unscathed.</p>
<p>Ideally you should avoid these scenarios altogether by redesigning your code in such a way that the right-hand-side object is not affected by the copy (Note that smart pointers may have helped me avoid this scenario).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2005/03/23/writing-copyable-c-classes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Game Development Update</title>
		<link>http://www.codedread.com/blog/archives/2005/03/01/game-development-update/</link>
		<comments>http://www.codedread.com/blog/archives/2005/03/01/game-development-update/#comments</comments>
		<pubDate>Wed, 02 Mar 2005 05:51:10 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Entertainment]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[SDL]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">/?p=55</guid>
		<description><![CDATA[I just spent the last few nights working on the user-interface code of this SDL 2D strategy game that I&#8217;m working on. It&#8217;s finally come together nicely now. I had been under the philosophy much earlier on to just &#8220;do what it takes&#8221; to accomplish something without heavy regard for good design, etc. I now [...]]]></description>
			<content:encoded><![CDATA[<p>I just spent the last few nights working on the user-interface code of <a href="http://www.codedread.com/games.php#TNO">this SDL 2D strategy game that I&#8217;m working on</a>.  It&#8217;s finally come together nicely now.  <span id="more-55"></span></p>
<div class="ads"><object type="text/html" width="468" height="60" data="http://www.codedread.com/gads.php"></object></div>
<p>I had been under the philosophy much earlier on to just &#8220;do what it takes&#8221; to accomplish something without heavy regard for good design, etc.  I now have paid the price for that a few times, since as the code has evolved, I&#8217;ve had to redesign/refactor significant sections of code.</p>
<p>Anyway, I totally reworked the component hierarchy so graphical components of the user interface includes base Components with subclasses of Containers, Labels, Images.  All of these components can be bound to event handlers at run-time for the following mouse events: &#8220;onMouseEnter&#8221;, &#8220;onMouseExit&#8221;, &#8220;onMouseMove&#8221;, &#8220;onMousePressed&#8221;, &#8220;onMouseReleased&#8221; and &#8220;onMouseClicked&#8221;.  Each <a href="http://blog.codedread.com/archives/2005/02/03/matters-of-state-three/">game state</a> has a &#8220;desktop&#8221; container that contains the screen elements and components are added, initialized, positioned and sized and bound to events at run-time.  Events are forwarded to the desktop container which handles routing the events down the hierarchy.</p>
<p>This is all pretty basic UI component hierarchy stuff, and I&#8217;ve done similar frameworks before (in DirectX, for instance).  It&#8217;s a shame that I couldn&#8217;t reuse a lot of that stuff but it ends up being too specific (coordinate systems, pointers to surfaces, etc) that I end up re-inventing the wheel each time.  I&#8217;ll write another entry in a few days about that as I&#8217;ve been reading and practicing <a href="http://www.omg.org/uml/" title="Unified Modeling Language">UML</a> and <a href="http://www.amazon.com/exec/obidos/ASIN/0321179366/codedread-20" title="Object Constraint Language">OCL</a> at work.  <i>[Editor's Note: This never happened, sorry]</i></p>
<p>I guess I could have gone with one of the several <abbr title="Graphical User Interface">GUI</abbr> packages out there for <abbr title="Simple DirectMedia Layer">SDL</abbr> but this one sort of evolved from the current code and now I&#8217;m growing to like it.</p>
<p>Anyway, now that I have the basic UI component hierarchy in place, I&#8217;m going back into game code and start to implement the map rendering function that displays where the characters are in the school.  One of my first tasks once this is complete is to allow the user to scroll the map in any direction by dragging the map with the middle mouse button.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codedread.com/blog/archives/2005/03/01/game-development-update/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

