<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss'><id>tag:blogger.com,1999:blog-27397864</id><updated>2010-01-21T16:06:35.862-05:00</updated><title type='text'>The Write Better Code Forum</title><subtitle type='html'>A place where programmers can discuss various programming topics and experiences.</subtitle><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default'/><link rel='alternate' type='text/html' href='http://writebettercode.org/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://writebettercode.org/atom.xml'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>22</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-27397864.post-2798405517712704928</id><published>2009-09-13T11:53:00.001-04:00</published><updated>2009-09-13T11:54:14.689-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='VMware'/><title type='text'>VMworld 2009 - vSphere SDK Best Practices</title><content type='html'>&lt;p class="body"&gt;I've been back from San Francisco for a week now and finally have gotten around to writing up a note regarding my VMworld 2009 trip.&amp;#160; My trip started off with Monday's Tech Exchange and continued with 3 more days of general VMworld sessions ranging from lower-level API discussions to high-level marketing speak.&amp;#160; If I had to pick a favorite day, it would be the Tech Exchange.&amp;#160; It really is geared toward developers.&amp;#160; You get some great presentations and also a chance to meet those engineers whose APIs you might use (or frequently use as is my case).&amp;#160; Here are some tidbits I picked up regarding performance counter queries in the vSphere Web Services SDK:  &lt;ul&gt;   &lt;li&gt;First, when querying for performance counter information for a set of managed objects, there is no need to query for a &lt;code&gt;PerfProviderSummary&lt;/code&gt; if all your managed objects are of the same entity type (e.g. VirtualMachine, ClusterComputeResource, etc.).&amp;#160; A single query will suffice for an entity type as the "summary" will be the same for all entities of a single type.&amp;#160; Here's a quick code snippet which shows how to retrieve a &lt;code&gt;PerfProviderSummary&lt;/code&gt; object for a particular managed object reference:&lt;/li&gt; &lt;/ul&gt;&lt;/p&gt; &lt;pre&gt;
// The "entityMORef" variable is a ManagedObjectReferenceType for
// any particular entity we are monitoring (e.g. VirtualMachine,
// ResourcePool, etc.).
// The "perfManager" variable is a reference to the PerformanceManager
// retrieved as a property from the ServiceContent object.
// The "_service" object is the VimService object.

PerfProviderSummary summary =
    _service.QueryPerfProviderSummary(_sic.perfManager, entityMORef);
&lt;/pre&gt;
&lt;p class="body"&gt;
As in my case, if I'm querying for performance counters for a collection of 1,000 virtual machines, I only need to make this call once.  Previously, I'd been invoking this method for all 1,000 virtual machines on the first iteration of the query.  As you probably already know, if you are querying for performance counter information on a scheduled basis, there's no reason to make this call on every query iteration.  Make the call to &lt;code&gt;QueryPerfProviderSummary()&lt;/code&gt; on the first query and then cache those summary objects away (in your &lt;code&gt;PerfQuerySpec&lt;/code&gt; object(s)) for use in later queries.&lt;/p&gt;
&lt;p class="body"&gt;
&lt;ul&gt;
&lt;li&gt;Second, when querying for performance counter information be aware that said counters/metrics can change based on changes to the entity hardware.  For example, let's say you have a virtual machine entity who currently isn't configured with any virtual disks.  If you create a new virtual disk for this VM a number of new metrics will become available.  Therefore you need to make sure you requery the performance counter metric IDs for this particular entity.  This means a new call to the &lt;code&gt;QueryAvailablePerfMetric()&lt;/code&gt; method so that any new (or missing) &lt;code&gt;metricID&lt;/code&gt; objects can be retrieved.  Here's a sample of how to make this call:&lt;/li&gt;&lt;/ul&gt;&lt;/p&gt;
&lt;pre&gt;
// The "_service" object is the VimService object.
// Let's collect performance metrics for the last 5 minutes.
DateTime serverTime = _service.CurrentTime(serviceRef);
DateTime startTime = _service.AddMinutes(0 - 5);
DateTime endTime = serverTime;

// Query all available metrics for the managed object reference
int dataInterval = 30; // Note: this interval is for real-time metrics
PerfMetricId[] aMetrics = null;
try
{
    aMetrics = 
        _service.QueryAvailablePerfMetric(perfManagerRef,
                                          vmMORef,
                                          startTime,
                                          false,
                                          endTime,
                                          false,
                                          dataInterval,
                                          true);
 }
 catch (Exception)
 {
    // Some exception handling here...
}
&lt;/pre&gt;
&lt;p class="body"&gt;
&lt;ul&gt;
&lt;li&gt;
Lastly, if you are querying a large number of managed entities (e.g. 100+ virtual machines), it is better to use CSV format in your &lt;code&gt;PerfQuerySpec&lt;/code&gt; objects and this reduces the overall object serialization.  Metric information is returned in a comma-separated format and therefore the returned XML contains less objects.  This is the object serialization reduction I just mentioned.  You specify the counter query format in the &lt;code&gt;PerfQuerySpec&lt;/code&gt; object.  Here's a sample of how to set this property:
&lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;
&lt;pre&gt;
PerfQuerySpec spec = new PerfQuerySpec();
spec.entity = vmMORef;
spec.maxSample = 1;
spec.maxSampleSpecified = true;
spec.startTime = startTime;
spec.startTimeSpecified = true;
spec.endTime = endTime;
spec.endTimeSpecified = true;
spec.intervalId = dataInterval;
spec.intervalIdSpecified = true;

// Set your format to "csv"
spec.format = "csv";
&lt;/pre&gt;

&lt;p class="body"&gt;
This last tidbit will improve your performance queries significantly.  The only downside is that you now are required to parse the comma-separated values instead of iterating through an array of objects.  I plan on implementing this last portion ASAP b/c I usually am querying in excess of 500 VMs frequently and this will help my query time significantly.
&lt;/p&gt;

&lt;p class="body"&gt;- Gilemonster&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-2798405517712704928?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/2798405517712704928/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=2798405517712704928&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/2798405517712704928'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/2798405517712704928'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2009/09/vmworld-2009-vsphere-sdk-best-practices.html' title='VMworld 2009 - vSphere SDK Best Practices'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-6281124155125562401</id><published>2009-07-02T10:40:00.000-04:00</published><updated>2009-07-02T10:42:54.609-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='VMware'/><title type='text'>VMworld 2009 - San Francisco, CA</title><content type='html'>&lt;p class="body"&gt;I've been working in a virtualized environment now for a good 12 - 14 months and I have to say I'm very impressed with everything.&amp;#160; VMware has really got their stuff together and I have even enjoyed using their &lt;a href="http://www.vmware.com/support/developer/vc-sdk/" target="_blank"&gt;vSphere Web Services SDK&lt;/a&gt;.&amp;#160; It is complicated to understand at first but once you grasp the high-level layout and structure of their environment it is much nicer than other 3rd party APIs I've used in the past.&lt;/p&gt;  &lt;p class="body"&gt;Because of my recent work in this area I'm getting to travel to &lt;a href="http://www.vmworld.com/index.jspa" target="_blank"&gt;VMworld 2009&lt;/a&gt; in San Francisco, CA this year and I'm stoked.&amp;#160; It should be a real blast and contain tons of information for developers looking to implement solutions provided out of the various SDKs that VMware provides.&amp;#160; I hope to provide daily highlights to let everyone know what is going on (no, I don't believe in twitter)!&lt;/p&gt;  &lt;p class="body"&gt;- Gilemonster&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-6281124155125562401?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/6281124155125562401/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=6281124155125562401&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/6281124155125562401'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/6281124155125562401'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2009/07/vmworld-2009-san-francisco-ca.html' title='VMworld 2009 - San Francisco, CA'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-8774984117805123348</id><published>2008-04-04T14:02:00.002-04:00</published><updated>2008-04-04T17:00:09.941-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Bitten by an STL Gotcha...again</title><content type='html'>&lt;p class="body"&gt;I was recently using an STL map container and hit one of those "STL gotchas" that I had forgotten about.&amp;nbsp; I figured I would pass along what I found and the changes I made.&amp;nbsp; As everyone already knows an STL map is a sorted associated container which takes a key-value pair.  The existing code I had, which was using an &lt;code&gt;std::map&lt;/code&gt;, actually contained unique key-value pairs.  What I mean is that each pair was only inserted into the map once and the pairs were never updated by inserting the same key twice.  When I went to change this code I realized I would need to change the values of existing items in the map.  Here's some sample code to explain what I was doing:&lt;/p&gt; &lt;pre&gt;

typedef std::map&amp;lt;std::wstring, std::wstring&amp;gt; MyMap;
typedef std::pair&amp;lt;std::wstring, std::wstring&amp;gt; MyMapEntry;

// Insert a value with key "MyKey".
MyMap theMap;
theMap.insert(MyMapEntry(L"MyKey", L"MyValue1"));

// Update the value associated with key "MyKey."
theMap.insert(MyMapEntry(L"MyKey", L"MyValue2"));

&lt;/pre&gt;
&lt;span class="fullpost"&gt;&lt;p class="body"&gt;When I went to run this code and iterated through my map I noticed that the value associated with key &lt;code&gt;"MyKey"&lt;/code&gt; was actually &lt;code&gt;"MyValue1"&lt;/code&gt;!!!  What the heck is going on?  Well, the &lt;code&gt;insert()&lt;/code&gt; routine is a little tricky here (evil if you ask me).  If you are inserting a new item into the map, everything works fine.  If you are attempting to &lt;i&gt;overwrite&lt;/i&gt; an existing item, it sees that it is there and doesn't update it.  Nice...  So, I tried the use of &lt;code&gt;operator[]&lt;/code&gt; to update my map and this worked.  Here's what the second iteration (no pun intended) of the code looked like:&lt;/p&gt;
&lt;pre&gt;

typedef std::map&amp;lt;std::wstring, std::wstring&amp;gt; MyMap;
typedef std::pair&amp;lt;std::wstring, std::wstring&amp;gt; MyMapEntry;

// Insert a value with key "MyKey".
MyMap theMap;
theMap[L"MyKey"] = L"MyValue1";

// Update the value associated with key "MyKey."
theMap[L"MyKey"] = L"MyValue2";

&lt;/pre&gt;
&lt;p class="body"&gt;So, now that it is working I should just let it go right?  &lt;B&gt;Wrong.&lt;/B&gt;  I remembered a Scott Meyer's article awhile back where he mentioned how each of the mechanisms for inserting/updating items in a map can affect efficiency based on how you use them.  Here's the basic gist of things:&lt;/br&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;insert&lt;/code&gt; should only be used to insert new items into a map.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;operator[]&lt;/code&gt; should only be used to update existing items.&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="body"&gt;But this is obviously a royal pain because how do you know if an item is already in a map without searching for it first?  It can't be more efficient to search for an item first and then decide how to insert/update it?  This is where &lt;code&gt;lower_bound&lt;/code&gt; comes into play.  This routine will return an iterator to the first element in a container with a key that is equal to or greater than a given key.  Once you get an iterator to that point in the map you can determine if the key really exists by invoking &lt;code&gt;key_comp&lt;/code&gt;.  If the key matches, you know you've found your existing item and you can update it.  If the key doesn't match you now have an iterator to where that item SHOULD be inserted into the map.  So this "search" operation is not wasted after all.  You can use this location "hint" to insert your new item into the map.  Meyers also mentioned that &lt;code&gt;insert&lt;/code&gt; will run in amortized constant-time because of the hint.  So here's how you would write the earlier example given what we know now:&lt;/p&gt;
&lt;pre&gt;

typedef std::map&amp;lt;std::wstring, std::wstring&amp;gt; MyMap;
typedef std::pair&amp;lt;std::wstring, std::wstring&amp;gt; MyMapEntry;

// Insert a value with key "MyKey".
MyMap theMap;
theMap.insert(MyMapEntry(L"MyKey", L"MyValue1"));

// Assume you don't know whether an item has already been inserted
// after this point *grin*
MyMap::iterator iter = theMap.lower_bound(L"MyKey");
if ((theMap.end() != iter) &amp;&amp; 
     !(theMap.key_comp()(L"MyKey", iter-&gt;first)))
{
    iter-&gt;second = L"MyValue2";
}
else
{
    theMap.insert(iter, MyMapEntry(L"MyKey", L"MyValue2"));
}

&lt;/pre&gt;
&lt;p class="body"&gt;Now the example above is pretty simple but when you have code that performs a number of insertions in numerous locations, it is easy to not know whether an item exists in a map.  You could write a template function as well (which is what I did).  Until next time...&lt;br&gt;&lt;br&gt;
- Gilemonster&lt;/p&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-8774984117805123348?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/8774984117805123348/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=8774984117805123348&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/8774984117805123348'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/8774984117805123348'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2008/04/bitten-by-stl-gotchaagain.html' title='Bitten by an STL Gotcha...again'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-926071360275638013</id><published>2007-04-21T12:32:00.001-04:00</published><updated>2007-04-21T15:31:12.589-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='General'/><title type='text'>Practices of an Agile Developer</title><content type='html'>&lt;p class="body"&gt;I just finished reading &lt;a title="Pragmatic Bookshelf" href="http://www.pragmaticprogrammer.com/titles/pad/index.html" target="_blank"&gt;&lt;em&gt;Practices of an Agile Developer&lt;/em&gt;&lt;/a&gt;&lt;em&gt;&amp;nbsp;&lt;/em&gt;(by Venkat Subramaniam &amp;amp; Andy Hunt)&amp;nbsp;and I wanted to recommend it to those people who want to learn about the Agile process or just want to help improve their own code quality and performance.&amp;nbsp; Of all the methodolgies and processes that make up Agile (or rather allow it to fit to your environment) there are a core set of practices that this book points out.&amp;nbsp; It&amp;nbsp;takes these practices and shows the reader how to apply them to their daily workload.&amp;nbsp; Here's a great &lt;a title="A Practical Agile book - The Register" href="http://www.regdeveloper.co.uk/2006/10/10/practices_agile_developer/" target="_blank"&gt;review&lt;/a&gt; of the book that I recommend as well (why should I write the review when someone has already done it for me?).&amp;nbsp; Go out and buy this.&amp;nbsp; It's worth the $30 price tag.&lt;br&gt;&lt;br&gt; - Gilemonster&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-926071360275638013?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/926071360275638013/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=926071360275638013&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/926071360275638013'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/926071360275638013'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2007/04/practices-of-agile-developer.html' title='Practices of an Agile Developer'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-116637542510069282</id><published>2006-12-17T12:10:00.000-05:00</published><updated>2007-04-21T15:28:32.432-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>ATL 7.0 String Conversion Classes</title><content type='html'>&lt;p class="body"&gt; If you've ever written Win32 code that is compiled for both ANSI and Unicode you've probably used the ATL 3.0 string conversion classes and their macros (e.g. W2A, A2W, T2A, A2T, etc.). They have been very useful but unfortunately have problems. Microsoft has alleviated a number of these issues in ATL version 7.0. This article gives a brief overview of those fixes and how the use of these classes has improved in version 7.0.&lt;/p&gt; &lt;p class="body"&gt; ATL 3.0 string conversion had the following problems which are fixed in version 7.0.  &lt;ul&gt; &lt;li&gt;Usage not safe in loops.  &lt;li&gt;Usage not safe in exception catch blocks.  &lt;li&gt;Requires &lt;code&gt;USES_CONVERSION&lt;/code&gt; to be defined.  &lt;li&gt;Large strings stored on the heap where space is limited. &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;/p&gt; &lt;p class="body"&gt; The main reason why ATL 3.0 had issues relates to where strings are stored and when they are freed. All converted strings were stored on the stack and they were not freed until the calling function returned. This means that if you had a routine that never returned (i.e. a separate "watch-dog" thread that never returns unless your application stops running) your converted strings were never freed. This could put tremendous strain on a thread's stack because of how large a string is and how often they are allocated. In version 7.0, the ATL now destructs the string when the object goes out of scope. It also checks the size of the string and if it is too large for the stack, it will store the string on the heap. So, small strings will be stored on the stack, but large ones will be allocated on the heap. Because the strings are destructed when they go out of scope, it is now safe to use the classes in loops because you know that when a loop iteration completes, the string will be destructed. This also makes them safe for use in exception handling code (e.g. &lt;code&gt;catch(MyException &amp;e)&lt;/code&gt;). Another nice improvement is the ability to leave that pesky &lt;code&gt;USES_CONVERSION&lt;/code&gt; definition out of your code. It always annoyed me and I'm glad to see it go. :-)&lt;/p&gt; &lt;p class="body"&gt; Now that we've seen a quick overview of how the new classes are safer, let's look at how to use them because it is drastically different and if used like the older macro code you &lt;b&gt;will&lt;/b&gt; get undefined results. If you want to use the new macros, you'll need to change your code. Below is the form of the macros that I stole from the MSDN:&lt;br&gt;&lt;br&gt;&lt;code&gt;CSourceType2[C]DestinationType[EX]&lt;/code&gt;&lt;br&gt;&lt;br&gt; where:  &lt;ul&gt; &lt;li&gt;&lt;code&gt;[C]&lt;/code&gt; is present when the destination type must be constant.  &lt;li&gt;&lt;code&gt;[EX]&lt;/code&gt; is present when the initial size of the buffer must be specified as a template argument.  &lt;li&gt;&lt;code&gt;SourceType/DestinationType&lt;/code&gt; can be the following:  &lt;ul&gt; &lt;li&gt;&lt;code&gt;A&lt;/code&gt; - ANSI character string  &lt;li&gt;&lt;code&gt;W&lt;/code&gt; - UNICODE character string  &lt;li&gt;&lt;code&gt;T&lt;/code&gt; - Generic character string (determined at compile time).  &lt;li&gt;&lt;code&gt;OLE&lt;/code&gt; - OLE character string (equivalent to W). &lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt; &lt;/p&gt; &lt;p class="body"&gt; &lt;span class="fullpost"&gt; Here are some simple examples of how to use the new macros.  Note:  I hate &lt;code&gt;LPCSTR&lt;/code&gt; and &lt;code&gt;LPWCSTR&lt;/code&gt; so you'll always see me use &lt;code&gt;char *&lt;/code&gt; and &lt;code&gt;wchar_t *&lt;/code&gt; whenever I can (probably not a good practice though).  :-)&lt;/p&gt; &lt;pre&gt;
// Figure 1:
// Convert a UNICODE string to ANSI.
void 
ConvertUnicodeToAnsi(wchar_t * pszWStr)
{
   // Create a local instance of the CW2AEX class and construct
   // it using a wchar_t *.
   // Note:  Here you will notice that I am using CW2A which is 
   // a typedef macro of the CW2AEX class.
   CW2A pszAStr(pszWStr);

   // Note: pszAStr will become invalid when it goes out of 
   // scope.  In this example, that is when the function
   // returns.
}
&lt;/pre&gt;
&lt;pre&gt;
// Figure 2:
// How to use a temporary instance of the CA2WEX class.
void
UseTempConvertedString(char * pszAStr)
{
   // Create a temporary instance of the CA2WEX class
   // and use it as a parameter in a function call.
   SomeSampleFunction(CA2W(pszAStr));

   // Note the temporary instance created in the
   // above call is only valid in the SomeSampleFunction
   // body.  Once the function returns, the temporary
   // string is destructed and no longer valid.
}
&lt;/pre&gt;
&lt;pre&gt;
// Figure 3:
// How NOT to use the conversion macros and classes.  This
// example uses the new classes but applied using the old
// programming style.
void
BadFunction(wchar_t * pszWStr)
{
   // Create a temporary instance of CW2A, save a 
   // pointer to it and then use it.
   char * pszAStr = CW2A(pszWStr);

   // The pszAStr variable in the following line is an invalid pointer,
   // as the instance of CW2A has gone out of scope.
   ExampleFunctionA(pszAStr);
}
&lt;/pre&gt;
&lt;p class="body"&gt;
Figures 1 and 2 are pretty straight forward, but Figure 3 should be discussed further.  In ATL 3.0, this is how we used the conversion classes.  It should be noted that this code structure is no longer valid and will produce undefined results.  Because of the new scoping of the conversion libraries, an invocation of the CW2AEX constructor cannot be used as we would expect.  Figure 3 shows that the &lt;code&gt;pszAStr&lt;/code&gt; variable &lt;b&gt;does not&lt;/b&gt; contain a valid pointer even though it appears it should.  If you need a converted string throughout the scope of a function, you should declare a local instance of the CW2AEX class on the stack and use the appropriate parameters during object construction (e.g. &lt;code&gt;CW2A pszAStr(pszWStr);&lt;/code&gt;).&lt;/p&gt;
&lt;p class="body"&gt;
&lt;B&gt;Specify a Custom Buffer Size&lt;/B&gt;&lt;br&gt;
The default buffer size for the new ATL classes is 128 characters.  If you need to change the default buffer size for certain types of conversions, use the &lt;code&gt;EX&lt;/code&gt; macros and specify a new buffer size.  This is defined as a C++ template.  Here is an example:&lt;/p&gt;
&lt;pre&gt;
// Figure 5:
// Specify a new buffer size with C++ template syntax.
void
UseCustomBufferSize(wchar_t * pszWStr)
{
   // Use a 16-character buffer.
   SomeFunction(CW2CAEX&lt; 16 &gt;(pszWStr));
}
&lt;/pre&gt;
&lt;p class="body"&gt;
The new ATL 7.0 string conversion classes are a much needed improvement over their 3.0 siblings.  Of course you don't have to change all your code to use them if you don't want to.  If you are concerned about application performance then you should consider updating your code.  You will be able to use the classes in a number of places previously unavailable and that is pretty convenient.  You can remove your old "work-around" code because of the safety of the new classes.  I plan on looking at my own code and estimating how much it will take to upgrade my ATL usage to version 7.0.  I might not be able to make the full change but I am least going to look at what the cost/benefit ratio is.  And for new code I'll only use the new 7.0 classes.  You should at least consider the same.  Until next time...&lt;br&gt;&lt;br&gt;
- Gilemonster&lt;/p&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-116637542510069282?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/116637542510069282/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=116637542510069282&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/116637542510069282'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/116637542510069282'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/12/atl-70-string-conversion-classes.html' title='ATL 7.0 String Conversion Classes'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-116278608978732492</id><published>2006-11-05T23:08:00.000-05:00</published><updated>2007-04-21T15:28:32.432-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Exception Handling Warnings in Visual Studio</title><content type='html'>&lt;p class="body"&gt; Have you ever seen this cryptic little C++ compiler warning before in Visual Studio 7.x (.NET 2003)?&lt;br&gt;&lt;br&gt;&lt;b&gt;cl: Command line warning D4025: overriding '/EHs' with '/EHa'&lt;/b&gt;&lt;br&gt;&lt;br&gt;I've seen it a number of times but always ignored it because other articles have said that "the compiler knows better." Well, the compiler might know better but I want to know why it knows better. So let's dissect this warning.&lt;/p&gt; &lt;p class="body"&gt; In Visual Studio, you can specify the Exception Handling model in the &lt;i&gt;Code Generation&lt;/i&gt; property page of a C++ project. What you are selecting is whether or not the compiler uses an &lt;i&gt;asynchronous exception model&lt;/i&gt; or a &lt;i&gt;synchronous exception model&lt;/i&gt;. The asynchronous model is an older exception handling mechanism where the compiler assumes any instruction can generate an exception (hardware). This significantly increases the overall code size because the compiler must have mechanics for tracking the lifetime of objects that cannot unwind. The synchronous model is new and tells the compiler that exceptions can only be thrown with a &lt;b&gt;throw&lt;/b&gt; statement. Because the compiler can now assume that exceptions will only be thrown by a &lt;b&gt;throw&lt;/b&gt; statement or at a function call, all that extra object lifetime tracking code is not supplied by the compiler. The MSDN states that hardware exceptions can still be caught using the synchronous model, "... However, some of the unwindable objects in the function where the exception occurs may not get unwound, if the compiler judges their lifetime tracking mechanics to be unnecessary for the synchronous model."&lt;/p&gt; &lt;p class="body"&gt; So how in the world did you get the aforementioned compiler warning in the first place? There are a couple of things to look for.  &lt;ul&gt; &lt;li&gt;First, verify that your command line doesn't specify both '/EHs' and '/EHa'.  You cannot specify both exception handling models.&lt;/li&gt; &lt;li&gt;Second, verify that your code isn't using structured exception translators (i.e. &lt;code&gt;_set_se__translator()&lt;/code&gt;). &lt;/li&gt; &lt;/ul&gt;&lt;/p&gt; &lt;p class="body"&gt; &lt;b&gt;Note&lt;/b&gt;: Structured exception translators (for the uninitiated) are used so that C exceptions (raised always as of type &lt;code&gt;unsigned int&lt;/code&gt; as opposed to C++ exceptions which can be raised of any type) can be handled by a C exception wrapper class and therefore attributed a type. This allows a matching C++ catch handler to catch a C exception. If you have C code mixed in your C++ project that uses structured exception translators, you will have to use the asynchronous exception model or the compiler will throw the above warning.&lt;/p&gt; &lt;p class="body"&gt; In VS 7.x, it has been documented that the inability to select the asynchronous exception model ('/EHa') in the project properties dialog was a bug. To get around this in 7.x, you need to select "No" for the "Enable C++ Exceptions" property. Then go to the "Command Line" property and add "/EHa" in the "Additional options" section. This will allow you to enable C++ exceptions in your projects. Here's a &lt;a title="Visual Studio .NET 2003 Exception Handling Options" href="http://writebettercode.org/pics/VS_2003_Exceptions.JPG" target="_blank"&gt;screenshot&lt;/a&gt; of the VS 2003 .NET C++ Code Generation properties dialog. This bug was fixed in version 8 and you can now select "Yes" to the "Enable C++ Exceptions" property with a value of "Yes With SEH Exceptions (/EHa)."  Here's a &lt;a title="Visual Studio 2005 Exception Handling Options" href="http://writebettercode.org/pics/VS_2005_Exceptions.JPG" target="_blank"&gt;screenshot&lt;/a&gt; of the updated dialog.&lt;/p&gt; &lt;p class="body"&gt; For my particular project, I had some C code that used structured exception translators.  So that was the reason for my warning.  Therefore, I disabled the option above, and added "/EHa" as an additional command line property option.  In general, enabling C++ exceptions in your VS projects should always be considered thoroughly (required in my opinion) and you should never disregard warnings like this one (as I did). For this particular case, the compiler was smart enough to fix the setting at build time, but that is not always the case. Know and understand your project settings and fix all warnings if possible.  Until next time...&lt;br&gt;&lt;br&gt; - Gilemonster&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-116278608978732492?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/116278608978732492/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=116278608978732492&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/116278608978732492'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/116278608978732492'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/11/exception-handling-warnings-in-visual.html' title='Exception Handling Warnings in Visual Studio'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-116275070051020433</id><published>2006-11-05T13:18:00.000-05:00</published><updated>2007-04-21T15:28:32.432-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Quick Observation on STL string Comparisons</title><content type='html'>&lt;p class="body"&gt;I was looking through some code this week and I noticed a few lines of code that caught my eye. The lines of code were doing basic STL string comparison using the non-member overloaded &lt;code&gt;operator==&lt;/code&gt; function. I remembered that the STL also provides an overloaded set of &lt;code&gt;compare&lt;/code&gt; functions for strings and wondered why you would use the overloaded operator functions instead of &lt;code&gt;compare&lt;/code&gt;. I did a bit of reading and found that there are reasons for using one over the other.&lt;/p&gt; &lt;p class="body"&gt;The easiest of the comparison mechanisms is obviously to use &lt;code&gt;operator==&lt;/code&gt;. You can use it to compare string objects, string literals that are quoted, and traditional C-style string pointers. The nice thing is that it (and other &lt;code&gt;operator&lt;/code&gt; routines) doesn't have to create temporary string objects. Here's a simple example:&lt;/p&gt;&lt;pre&gt;#include &amp;lt;string&amp;gt;
using namespace std;

std::wstring strFirstName = L"Billy";

if (L"Billy" == strFirstName)
{
    // Do something
}
else if (L"BILLY" == strFirstName)
{
    // Do something else
}
else if (L"BillyBoy" == strFirstName)
{
    // Do something else
}

&lt;/pre&gt;
&lt;p class="body"&gt;The above sample shows the simplicity of using &lt;code&gt;operator==&lt;/code&gt;. It also should show that its use should be limited to comparing simple character sets or single characters. A value of &lt;code&gt;true&lt;/code&gt; will only be returned when the two character sets being compared match identically with respect to length and ASCII character code (meaning "A" != "a").&lt;/p&gt;
&lt;span class="fullpost"&gt;
&lt;p class="body"&gt;The &lt;code&gt;compare&lt;/code&gt; routines provide a mechanism for performing &lt;i&gt;lexical comparisons&lt;/i&gt; and other more precise string comparisons. Instead of returning &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt;, three values are returned. 
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;0&lt;/code&gt;: the operand string is lexically equal to the parameter string. 
&lt;li&gt;&lt;code&gt;1&lt;/code&gt;: the operand string is greater than the parameter string. 
&lt;li&gt;&lt;code&gt;-1&lt;/code&gt;: the operand string is less than the parameter string. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p class="body"&gt;You can also use the other overloaded &lt;code&gt;compare&lt;/code&gt; routines to further specify what your lexical queries compare. Here are some examples.&lt;/p&gt;&lt;pre&gt;#include &amp;lt;string&amp;gt;
using namespace std;

wstring strOperand = L"Billy Bob",
        strParameter = L"Billy Bob's Barbecue";

// Standard use of compare
int intComparisonVal = strOperand.compare(strParameter);

// Further specification examples
size_type iOperandStartIndex = 0,
          iNumOperandCharsToCompare = 5;

// The second example specifies the starting index of the operand
// string and how many characters in the operand string to compare.  
// So you can compare part of the operand string with the parameter
// string.
intComparisonVal = strOperand.compare(iOperandStartIndex,
                                      iNumOperandCharsToCompare,
                                      strParameter);

// The third example goes further by also specifying the starting 
// index of the parameter string and how many characters to compare 
// in the parameter string.  So you can specify part of the operand
// string with part of the parameter string.
size_type iParamStartIndex = 0,
          iNumParamCharsToCompare = 5;
intComparisonVal = strOperand.compare(iOperandStartIndex,
                                      iNumOperandCharsToCompare,
                                      strParameter,
                                      iParamStartIndex,
                                      iNumParamCharsToCompare);

// My last example shows how to compare the operand string against
// a standard C-style string.
const wchar_t * strParameterCStyle = L"Billy Bob's Barbecue";
intComparisonVal = strOperand.compare(strParameterCStyle);

&lt;/pre&gt;
&lt;p class="body"&gt;There are other examples that further demonstrate the remaining overloaded &lt;code&gt;compare&lt;/code&gt; routines which I have left out for simplicity. And you can see that they give you the ability to lexically compare STL strings and C-style strings with greater precision than using the non-member &lt;code&gt;operator==&lt;/code&gt;. But, when do you choose one over the other and what are the details? Here's what I have learned as a set of general guidelines concerning STL string comparisons: 
&lt;ul&gt;
&lt;li&gt;When doing simple string comparisons where you want to exclude any unneeded overhead, use the operator routines. They first compare the operand and parameter string lengths and only if they are equal does it do a character by character ASCII value code comparison. 
&lt;li&gt;When you need more precise comparisons, use the &lt;code&gt;compare&lt;/code&gt; routines as desired. You can compare substrings which is more useful than an "all or nothing" string comparison where applicable. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p class="body"&gt;So, after reading all this mess I went back and examined the code mentioned at the beginning of this article. The code was written correctly and the string comparison was being used correctly. Anyway, I thought this was a quick and simple topic. Until next time...&lt;br&gt;&lt;br&gt;- Gilemonster&lt;/p&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-116275070051020433?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/116275070051020433/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=116275070051020433&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/116275070051020433'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/116275070051020433'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/11/quick-observation-on-stl-string.html' title='Quick Observation on STL string Comparisons'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-116208040054795270</id><published>2006-10-28T20:26:00.000-04:00</published><updated>2007-04-21T15:31:12.590-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='General'/><title type='text'>An ADO and VBScript Adventure</title><content type='html'>&lt;div xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;p class="body"&gt;In a recent work-related project I was asked to provide a simple VBScript code snippet that called a SQL stored procedure. No one knew what the stored proc looked like or even how it worked. To make matters worse, I am neither a T-SQL nor VBScript &lt;i&gt;guru&lt;/i&gt; by any degree. The task of writing that small bit of code is the topic of this article. If you are a VBScript or ADO guru, you can stop here as you'll probably not learn anything. You might get a laugh out of it though. ;-) If you are new to writing ADO code in VBScript (as I was), read on as I'll show you some pitfalls and things I didn't know (but unfortunately hit).&lt;/p&gt; &lt;p class="body"&gt;The stored procedure in question lived on a SQL Server 2000 machine, and to my surprise, contained over 100 parameters (all of which contained "default" values but 1)! The only required parameter was a GUID and was easily found in another table. So I figured I would test the stored proc out first in Microsoft's SQL Query Analyzer and make sure it worked as described. With my very little SQL experience, I just created the syntax that would call the stored proc and pass in 1 &lt;code&gt;GUID&lt;/code&gt; and 99 &lt;code&gt;NULL&lt;/code&gt; values. I thought that a &lt;code&gt;NULL&lt;/code&gt; value parameter would cause the stored proc to use its &lt;i&gt;default&lt;/i&gt; value. Oh how I was wrong! Instead of using default values, &lt;code&gt;NULL&lt;/code&gt; was treated as an acceptable value and therefore passed in to the remaining 99 parameters. You can imagine the damage that was done. I basically had used this stored proc to set every one of this table's foreign keys to NULL. So I pretty much destroyed the database. Nice... After many database restores, a coworker explained to me the problem with using &lt;code&gt;NULL&lt;/code&gt;. The correct thing to do was to pass the T-SQL keyword &lt;code&gt;DEFAULT&lt;/code&gt; as the parameter value and the stored proc will then use its default values (if any). Man, I felt like an idiot. What programmer thinks that &lt;code&gt;NULL&lt;/code&gt; wouldn't be an acceptable value? ;-) Even though I was thoroughly embarrassed, I figured the frustration was over and that I was golden. So I proceeded to write the sample VBScript which would do the same thing as the code in Query Analyzer. Here's a subset of the code I wrote (error checking removed for simplicity):&lt;/p&gt;&lt;span class="fullpost"&gt;&lt;pre&gt;Const adCmdStoredProc = 4
Const adGUID = 72
Const adParamInput = 1
Const adVarChar = 200
Const MyGuid = "1A8A3DA2-1564-40FA-8F4B-4B27B5B2BAD5"

'# Create your connection object to the SQL database
Dim objConnect
Set objConnect = CreateObject("ADODB.Connection")
objConnect.ConnectionString = "Provider=SQLOLEDB; " &amp;amp;_
                              "Data Source=MyServer; " &amp;amp;_
                              "Initial Catalog=MyDb; " &amp;amp;_
                              "Trusted_Connection=yes"

'# Setup your command object that will call the stored proc
Dim objCommand
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnect
objCommand.CommandType = adCmdStoredProc
objCommand.CommandText = "MyStoredProcName"

'# Supply the required parameters to the stored proc
Dim objParam1
Set objParam1 = objCommand.CreateParameter("@Param1", _
                                           adGUID, _
                                           adParamInput, _
                                           , _
                                           MyGuid)
objCommand.Parameters.Append objParam1

Dim objParam2
Set objParam2 = objCommand.CreateParameter("@Param2", _
                                           adVarChar, _
                                           adParamInput, _
                                           32, _
                                           "BlahBlah")
objCommand.Parameters.Append objParam2

objCommand.Execute

'# Tada!  It should work right?
&lt;/pre&gt;
&lt;p class="body"&gt;As you can see, I created &lt;code&gt;ADODB.Connection&lt;/code&gt; and &lt;code&gt;ADODB.Command&lt;/code&gt; objects. I then passed in only those values that I needed (just 2 in this case) for the stored proc to execute. The first of which was the only parameter that was required by the stored procedure. When I ran the code, all I did was foul up the database again. The parameters I supplied were passed in as the first and second parameters to the stored proc. It didn't even matter that I supplied the name of parameter as well. Wait, how can that be?!! Well of course, I was fuming after this. The deadline had passed and people were beginning to wonder why this little snippet of code wasn't complete yet. Drama sucks! After a few cigarettes and some time to calm down, I sat down with my favorite search tool. Google. So, as usual, I started googling, googling and more googling. On about the 5th try, I found a hit about 20 links down (who looks down 20 hits on a Google search?) that showed how to specify your &lt;code&gt;Command.Parameters&lt;/code&gt; collection when you want to use the default value for some of the parameters. Here's the fix:&lt;/p&gt;&lt;pre&gt;...
Dim objCommand
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnect
objCommand.CommandType = adCmdStoredProc
objCommand.CommandText = "MyStoredProcName"
&lt;b&gt;objCommand.Refresh&lt;/b&gt;
...
objCommand.Parameters("@Param1") = MyGuid
objCommand.Parameters("@Param2") = "BlahBlah"
objCommand.Execute
&lt;/pre&gt;
&lt;p class="body"&gt;The &lt;code&gt;Refresh&lt;/code&gt; routine queries the database for the parameter list before you make your query. This means that you don't have to "create" any parameter objects for the Parameter collection that is in the &lt;code&gt;Command&lt;/code&gt; object. All you have to do is assign a value to the parameters that don't define a default value. Everything else not assigned a value to will not be set and therefore the stored proc will use the default values it defined. So as usual, I learned something new. Oh well, I'm not a big fan of VBScript or stored procedures anyway. In fact, I think languages that &lt;b&gt;aren't&lt;/b&gt; compiled were created by the Devil. ;-) Just kidding, they have their place and uses I guess. Anyways, here's what I can pass on to you (unless you just read this for a good laugh):&lt;/p&gt;
&lt;p class="body"&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;NULL&lt;/code&gt; is a valid value type when passed into a stored procedure parameter and therefore &lt;b&gt;does&lt;/b&gt; override the default value (if one is defined). In a tool like Query Analyzer, you need to specify either the &lt;code&gt;DEFAULT&lt;/code&gt; keyword, or the &lt;code&gt;@ParamName=DEFAULT&lt;/code&gt; alternative syntax. I'm sure there might be other ways to do this, but those are the ones I found. 
&lt;li&gt;In VBScript, make sure you query the database for a list of parameters before you try and pass them to a stored procedure (unless there are no parameters of course). You do this with the &lt;code&gt;ADODB.Command.Parameters.Refresh&lt;/code&gt; routine, and then you will be able to supply only those parameters you need and the rest will be treated as having no value at all. A side benefit is not having to write the code that creates and defines those parameter objects. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p class="body"&gt;This might have been a silly article, but maybe by some freak chance I'm not the only person in the world who didn't know that stuff. Hopefully somebody else will find it useful. Many more articles like this and people won't read this blog anymore. ;-) Until next time...&lt;br&gt;&lt;br&gt;- Gilemonster&lt;/p&gt;&lt;/span&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-116208040054795270?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/116208040054795270/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=116208040054795270&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/116208040054795270'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/116208040054795270'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/10/ado-and-vbscript-adventure.html' title='An ADO and VBScript Adventure'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-115841609125010186</id><published>2006-10-17T18:25:00.000-04:00</published><updated>2008-01-03T08:36:27.633-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='dotNet'/><title type='text'>.NET Generics and Native Code Sharing</title><content type='html'>&lt;div xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;p class="body"&gt;Sorry for the break in articles but work has been extremely time consuming. Hopefully, I can find some time to write more articles. Anyways, now for the goodies. If you are like you me, you have been playing ".NET catch-up" trying to read as many version 2.0/3.0 .NET articles as quickly as possible. I recently have been reading up on &lt;i&gt;Generics&lt;/i&gt; in the MSDN's &lt;a href="http://msdn2.microsoft.com/en-us/library/67ef8sbd.aspx"&gt;C# Programming Reference&lt;/a&gt; and it is a very exciting addition to the .NET framework. Specifically I want to talk about how it reduces code bloat through &lt;i&gt;native code sharing&lt;/i&gt;. I'll start with a quick overview of &lt;i&gt;Generics&lt;/i&gt;, how it is compiled, and then how code sharing is provided at runtime.&lt;/p&gt; &lt;p class="body"&gt;&lt;b&gt;Generics who?&lt;/b&gt;&lt;br&gt;&lt;i&gt;Generics&lt;/i&gt; is a language extension that allows programmers to parameterize the use of types. It allows classes, interfaces, structs, delegates, and methods to parameterize the data they manipulate and store (if you've ever used C++ templates the syntax will appear familiar). When declaring the constructs just mentioned, you simply replace the type of object being manipulated with what is called a &lt;i&gt;type parameter&lt;/i&gt;. You are also allowed to specify more than one &lt;i&gt;type parameter&lt;/i&gt; if needed. Here is a simple example of a generic class in C#:&lt;/p&gt;&lt;pre&gt;using System;
using System.Text;
using System.Collections.Generic;

namespace WriteBetterCode
{
    public class MySimpleStack&amp;lt;T&amp;gt;
    {
        private int m_StackSize = 0;
        private int m_StackTopIndex = 0;
        T[] m_StackItems;

        public MySimpleStack(uint stackSize)
        {
            if (0 == stackSize)
            {
                m_StackSize = stackSize;
                m_StackItems = new T[m_StackSize];
            }
            else
            {
                throw new InvalidOperationException(
                    @"MySimpleStack must have a size greater
                    than zero!!!");
            }
        }

        public T Pop()
        {
            m_StackTopIndex--;
            if(m_StackTopIndex &amp;gt;= 0)
            {
                return m_StackItems[m_StackTopIndex];
            }
            else
            {
                m_StackTopIndex = 0;
                throw new InvalidOperationException(
                    "You popped an empty MySimpleStack!!!");
            }
        }

        public void Push(T newStackItem)
        {
            if(m_StackTopIndex &amp;gt;= m_StackSize)
            {
                throw new InvalidOperationException(
                    "The MySimpleStack is full!!!");
            }
            
            m_StackItems[m_StackTopIndex] = newStackItem;
            m_StackTopIndex++;
        }
    }

    public class TestMySimpleStack
    {
        static void Main()
        {
            try
            {
                MySimpleStack&amp;lt;int&amp;gt; stackOfInts = 
                    new MySimpleStack&amp;lt;int&amp;gt;(5);

                stackOfInts.Push(10);
                stackOfInts.Push(15);
                int intValue = stackOfInts.Pop();
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
// Figure 1 : MySimpleStack&amp;lt;T&amp;gt; generic class declaration 
//            and instantiation
&lt;/pre&gt;&lt;span class="fullpost"&gt;
&lt;p class="body"&gt;As you can see in the above example, the &lt;code&gt;MySimpleStack&lt;/code&gt; class uses the type parameter &lt;code&gt;T&lt;/code&gt; to specify that it is a generic type. In order to instantiate the generic type, you must replace that identifier with a &lt;i&gt;type argument&lt;/i&gt; (e.g. &lt;code&gt;int&lt;/code&gt; in the above example). The resulting type is called a &lt;i&gt;constructed type&lt;/i&gt; (e.g. &lt;code&gt;MySimpleStack&amp;lt;int&amp;gt;&lt;/code&gt;), of which there are two types:&lt;br&gt;
&lt;ul&gt;
&lt;li&gt;&lt;i&gt;Closed constructed type&lt;/i&gt;: a constructed type that does not contain any type parameters (e.g. &lt;code&gt;MySimpleStack&amp;lt;int&amp;gt; stackOfInts&lt;/code&gt;). 
&lt;li&gt;&lt;i&gt;Open constructed type&lt;/i&gt;: a constructed type that contains at least one type parameter (e.g. &lt;code&gt;MyOpenType&amp;lt;int, U&amp;gt; stackOfOpenTypes&lt;/code&gt;). &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p class="body"&gt;The .NET Framework also provides a number of built-in generic types for you. You can use those types in your code by referencing the &lt;code&gt;System.Collections.Generic&lt;/code&gt; namespace (click &lt;a href="http://msdn2.microsoft.com/en-us/library/system.collections.generic.aspx"&gt;here&lt;/a&gt; for a full list of generic types provided by the framework). One of the built-in generic types is the &lt;code&gt;Queue&amp;lt;T&amp;gt;&lt;/code&gt; class. Here is an example of how to use it:&lt;/p&gt;&lt;pre&gt;using System;
using System.Text;
using System.Collections.Generic;

namespace WriteBetterCode 
{
    public class TestQueue
    {
        static void Main()
        {
            Queue&amp;lt;int&amp;gt; myQueue = new Queue&amp;lt;int&amp;gt;();
            myQueue.Enqueue(5);
            int queuedVal = myQueue.Dequeue();
        }
    }
}
&lt;/pre&gt;
&lt;p class="body"&gt;So how is generic code compiled? At compile-time, the generic type is converted into IL and metadata, which contain additional information specifying that a type parameter is being used (this was a required update to the CLR in version 2.0 of the framework so that &lt;i&gt;Generics&lt;/i&gt; could supported). Other than that, a generic type is compiled just like any other type.&lt;/p&gt;
&lt;p class="body"&gt;&lt;b&gt;Native Code Sharing&lt;/b&gt;&lt;br&gt;Now we can get into the interesting stuff with &lt;i&gt;native code sharing&lt;/i&gt;. This is when two or more “compatible” method instantiations point to the same x86 code. So the shared code is the method code (e.g. &lt;code&gt;myQueue.Enqueue(int)&lt;/code&gt;) that operates on a particular type, not the instances themselves (e.g. &lt;code&gt;myQueue&lt;/code&gt;). They are still independent as expected.&lt;/p&gt;
&lt;p class="body"&gt;Of course, &lt;i&gt;native code sharing&lt;/i&gt; is provided at runtime by the JIT compiler &lt;b&gt;and&lt;/b&gt; it reacts differently for value and reference type arguments. At runtime, when the JIT is fed a type argument that is a value type, it replaces the type parameters in the IL with the actual value type and then generates the native code. So your runtime generated type becomes a collection where the value types are actually contained in the collection. The first time the JIT compiler is fed a type argument that is a reference type, it replaces the type parameters in the IL with &lt;code&gt;Object&lt;/code&gt; and then compiles that into native code. The native code sharing comes into play if the JIT is given a type argument for which it has already generated native code.&lt;/p&gt;
&lt;p class="body"&gt;When the JIT is fed a type argument, that is a value type, for which it has &lt;b&gt;already&lt;/b&gt; generated native code (an exact value type match), a reference to that native code is returned. It can do this because the JIT compiler keeps track of previously generated value-type-specific code. Note that native code sharing does not apply globally to value types in general. This means that all value types &lt;b&gt;do not&lt;/b&gt; share a single implementation. Conversely, reference types &lt;b&gt;do&lt;/b&gt; share a single implementation of the JIT generated native code. Since &lt;code&gt;Object&lt;/code&gt; replaces the type argument in the IL code, this code can be shared for any further requests (b/c reference sizes are the same).&lt;/p&gt;
&lt;p class="body"&gt;So you might be wondering why there is single implementation being shared for reference types, but not for value types. The reasoning for the reference type implementation is obvious. The size of a reference is always the same for any object and therefore the generated native code (that operates on the reference type) can be shared. Value types don't have the luxury of always being the same size. Even if two value types are the same size, you still can't share native code because the operations on different value types are not always the same. The only way to ensure that all types share a single implementation is to box/unbox all value types at runtime. The performance hit from this type of operation is detrimental to the performance of Generic types and therefore was intentionally left out of the .NET framework 2.0 implementation. But, if you have two constructed types whose type arguments are an exact value type match, they &lt;b&gt;do&lt;/b&gt; share their method implementations at the native code leve. Here's a quick example:&lt;/p&gt;&lt;pre&gt;using System;
using System.Text;
using System.Collections.Generic;

namespace WriteBetterCode 
{
    public class TestQueue
    {
        static void Main()
        {
            Queue&amp;lt;int&amp;gt; myQueue1 = new Queue&amp;lt;int&amp;gt;();
            Queue&amp;lt;int&amp;gt; myQueue2 = new Queue&amp;lt;int&amp;gt;();
            
            myQueue1.Enqueue(5);
            myQueue2.Enqueue(10);
            int queuedVal = myQueue1.Dequeue();
        }
    }
}
&lt;/pre&gt;
&lt;p class="body"&gt;The two &lt;code&gt;Queue&lt;/code&gt; variables above share method implementations generated by the JIT compiler (e.g. &lt;code&gt;Enqueue(&amp;lt;int&amp;gt;)&lt;/code&gt;).&lt;/p&gt;
&lt;p class="body"&gt;C++ templates, do not have any type of native code sharing. For example, if you instantiate 2 &lt;code&gt;vector&amp;lt;int&amp;gt;&lt;/code&gt; objects, the method code that operates on a &lt;code&gt;vector&amp;lt;int&amp;gt;&lt;/code&gt; object is generated separately twice and is a part of your program. This is the code bloat that I was talking about earlier. I'm sure you can imagine a scenario where your own STL applications could have a much smaller memory footprint if native code sharing was supported.&lt;br&gt;&lt;br&gt;- Gilemonster&lt;/p&gt;&lt;/span&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-115841609125010186?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/115841609125010186/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=115841609125010186&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115841609125010186'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115841609125010186'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/10/net-generics-and-native-code-sharing.html' title='.NET Generics and Native Code Sharing'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-115539756818157696</id><published>2006-08-15T10:19:00.000-04:00</published><updated>2007-04-21T15:28:32.433-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Know Your C++:  Virtual Functions</title><content type='html'>&lt;p class="body"&gt;
&lt;i&gt;Polymorphism&lt;/i&gt; is one of three programming paradigms that give a language the ability to support &lt;i&gt;object-oriented&lt;/i&gt; programming.  In C++ this is implemented via &lt;strong&gt;virtual functions&lt;/strong&gt;.  Before we can understand virtual functions, we must first learn about function call binding.
&lt;/p&gt;
&lt;p class="body"&gt;
When writing code, we frequently implement function declarations and definitions.  In order for the code to compile, the compiler must match up the function call with the address of the associated function body.  This process is known as  &lt;i&gt;binding&lt;/i&gt;.  When the compiler and linker are able to successfully match the two before code execution, it is called &lt;i&gt;early binding&lt;/i&gt;.  Because polymorphism requires binding at runtime, C++ must provide an additional mechanism in order to support this.  Matching the function call with its associated body at runtime is called &lt;i&gt;late binding&lt;/I&gt;.  C++ uses &lt;i&gt;virtual functions&lt;/i&gt; to support &lt;i&gt;late  binding&lt;/i&gt;.  When a function has the keyword &lt;i&gt;virtual&lt;/i&gt; prepended to its declaration, the C++ compiler knows that function call binding will occur at runtime.  Since compiler and linker know that a function body address will not be matched with an associated call at compile/link time, it creates a unique &lt;strong&gt;VTABLE&lt;/strong&gt; for each object type that contains virtual functions.  This table contains the addresses of each virtual function body for a particular object type.  Along with the VTABLE, a &lt;strong&gt;vpointer&lt;/strong&gt; (e.g. VPTR) is created/added to each object that is instantiated.  The vpointer points to the appropriate VTABLE for that particular object type.  So, for each object you create (that contains virtual functions), a vpointer is created, which knows the correct VTABLE to which it must point.  And, this VTABLE contains the addresses of all the function bodies for that object type.  So at runtime, your are guaranteed that your code will always have an associated function body for each function call.  Still with me?  Let's look at an example to clarify the concept.&lt;/p&gt;
&lt;pre&gt;
class Base
{
public:
    Base();
    ~Base();

    void PrintStuff();

    // Virtual function declaration
    &lt;strong&gt;virtual&lt;/strong&gt; long MorphMePlease();
};

// Virtual function definition
long
Base::MorphMePlease()
{
    return 0;
}

class Derived : public Base();
{
public:
    Derived();
    ~Derived();

    // Derived implements its own version of the
    // virtual function by using the same function
    // signature and removing the keyword &lt;strong&gt;virtual&lt;/strong&gt; 
    long MorphMePlease();
};

// Derived function definition that overrides the Base class'
// virtual function.
long
Derived::MorphMePlease()
{
    return 1;
}

// A non-class member function.
long 
SomeNonMemberFunction(Base * ptrObj)
{
    // If a Base pointer is passed to this function,
    // Base::MorphMePlease() is called.  If a Derived
    // pointer is passed to this function, Derived::MorphMePlease()
    // is called.
    return (ptrObj-&gt;MorphMePlease());
}
&lt;/pre&gt;
&lt;span class="fullpost"&gt;
&lt;p class="body"&gt;
In the above example you see that our &lt;code&gt;Base&lt;/code&gt; class implements a virtual function called &lt;code&gt;MorphMePlease()&lt;/code&gt; and that our &lt;code&gt;Derived&lt;/code&gt; class overrides that function with its own implementation.  Depending on what you pass into the non-member function &lt;code&gt;SomeNonMemberFunction()&lt;/code&gt; either the &lt;code&gt;Base&lt;/code&gt; or the &lt;code&gt;Derived&lt;/code&gt; class' function can be called.  How is that?  When a pointer to a &lt;code&gt;Derived&lt;/code&gt; object is passed in, it is implicitly &lt;i&gt;upcast&lt;/i&gt; to a &lt;code&gt;Base&lt;/code&gt; pointer.  Even though the cast is performed, the object's &lt;i&gt;vpointer&lt;/i&gt; is unchanged, and therefore still points to the VTABLE of &lt;code&gt;Derived&lt;/code&gt; function addresses.  This type of functionality demonstrates the ability to change functional behavior based on object type at runtime.  This is the &lt;i&gt;polymorphism&lt;/i&gt; we mentioned earlier.&lt;/p&gt;
&lt;p class="body"&gt;
So what happens with &lt;i&gt;pure virtual functions&lt;/i&gt;?  If by definition, they don't have a default definition, how does the compiler treat them?  Well, as we mentioned earlier, the compiler must guarantee that every function call be associated with a corresponding function body address.  If this were not guaranteed, we'd have all kinds of runtime errors when a function call was invoked that had no body (imagine the madness...).  When the compiler sees that an object type has a pure virtual function, it reserves a row in the VTABLE for the associated function body, but doesn't actually insert the address (b/c there isn't one).  Of course, this makes the VTABLE for that object type incomplete.  Since the table is incomplete, the compiler cannot guarantee safe execution of that object's code.  Because of this, the compiler will throw an error if an object of that type is instantiated anywhere in the compiled code.  Because you cannot actually instantiate this object type, it becomes what is known as an &lt;i&gt;abstract&lt;/i&gt; class type.  Let's take a look at our previous example using &lt;i&gt;pure virtual functions&lt;/i&gt; instead.&lt;/p&gt;
&lt;pre&gt;
class Base
{
public:
    Base();
    ~Base();

    void PrintStuff();

    // Pure virtual functions require that a 
    // derived class define the function body.
    virtual long MorphMePlease() &lt;strong&gt;= 0&lt;/strong&gt;;
};

class Derived : public Base();
{
public:
    Derived();
    ~Derived();

    // Derived class defines the function body
    // and is therefore allowed to be instantiated.
    long MorphMePlease();
};

// Derived function definition that defines the 
// Base class' pure virtual function
long
Derived::MorphMePlease()
{
    return 1;
}
&lt;/pre&gt;
&lt;p class="body"&gt;
In our updated example above, we notice the &lt;code&gt;Base::MorphMePlease()&lt;/code&gt; function declaration is assigned to zero.  That assignment signals to the compiler that a function is pure virtual (and therefore makes the class &lt;i&gt;abstract&lt;/i&gt;).  You will also notice that the &lt;code&gt;Base::MorphMePlease()&lt;/code&gt; function definition is not provided.  If you tried to provide one the compiler would barf and say you need to make up your mind b/w virtual and pure virtual functions (paraphrasing of course *grin*).  If you were to remove the declaration and definition of the &lt;code&gt;Derived::MorphMePlease()&lt;/code&gt; function, the &lt;code&gt;Derived&lt;/code&gt; class would also become &lt;i&gt;abstract&lt;/i&gt; and therefore not instantiatable.  This is because the &lt;code&gt;Derived&lt;/code&gt; object type's VTABLE would be incomplete as well.&lt;/p&gt;
&lt;p class="body"&gt;
Now that virtual functions and call binding have been explained, there are a few more points that need mentioning.  First, the initialization of the VTABLE and vpointer structures is performed during object construction.  The compiler provides this &lt;i&gt;hidden&lt;/i&gt; code for you in your constructor and therefore you don't have to write it.  Second, be careful about how you cast objects up/down the inheritance tree.  &lt;i&gt;Casting down&lt;/i&gt; or casting from a base object to a derived object is not guaranteed to work and has additional performance overhead.  This is because there is no runtime information which guarantees the downcast to succeed.  Therefore, an explicit cast is required.  It is safest to use the &lt;code&gt;dynamic_cast()&lt;/code&gt; function to cast a base object to its derived type.  &lt;code&gt;dynamic_cast()&lt;/code&gt; performs a runtime check to verify the cast will succeed and then performs the operation.  This additional runtime type verification is the performance overhead I hinted at earlier.  If you know more about your object hierarchy during downcasting you might be able to save the performance overhead of &lt;code&gt;dynamic_cast()&lt;/code&gt; and substitute it with &lt;code&gt;static_cast()&lt;/code&gt;.  &lt;code&gt;static_cast()&lt;/code&gt; doesn't perform the runtime check and there isn't guaranteed to be a safe operation.  The benefit is that it is faster than &lt;code&gt;dynamic_cast()&lt;/code&gt;.  If the downcast fails, it returns a NULL pointer to the calling code.  You just need to add a check for NULL before using the newly cast pointer.  &lt;i&gt;Casting up&lt;/i&gt;, on the other hand, is always safe.  A derived class object is &lt;i&gt;always&lt;/i&gt; a Base class object.  This casting is performed implicitly for you and doesn't require the use of code&gt;dynamic_cast&lt;/code&gt; or any other explicit cast code.&lt;/p&gt;
&lt;p class="body"&gt;
Virtual functions allow C++ to implement late binding and therefore polymorphic object behavior.  They can sometimes be a bit tricky to grasp, but once understood, they become a fundamental principle that C++ programmers rely on.  Until next time...&lt;br&gt;&lt;br&gt;
- Gilemonster&lt;/p&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-115539756818157696?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/115539756818157696/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=115539756818157696&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115539756818157696'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115539756818157696'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/08/know-your-c-virtual-functions.html' title='Know Your C++:  Virtual Functions'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-115384634292115833</id><published>2006-08-08T08:38:00.000-04:00</published><updated>2007-04-21T15:31:12.590-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='General'/><title type='text'>Know Your Data Structures:  Queues and Stacks</title><content type='html'>&lt;strong&gt;&lt;u&gt;Stacks&lt;/u&gt;&lt;/strong&gt;
&lt;p class="body"&gt;
A &lt;strong&gt;stack&lt;/strong&gt; is a dynamic linear data structure where insertion and deletion of items is already predetermined. This basically means that we already know where items are added and deleted before we perform the operation itself. Here's how it works. Stacks only allow you to insert and delete items from the top (or &lt;em&gt;tail&lt;/em&gt; of the stack). This logic flow is called &lt;em&gt;LIFO&lt;/em&gt; ("&lt;strong&gt;L&lt;/strong&gt;ast &lt;strong&gt;I&lt;/strong&gt;n &lt;strong&gt;F&lt;/strong&gt;irst &lt;strong&gt;O&lt;/strong&gt;ut") and means that the deletion of an item from the stack is always the item that was most recently added. A good analogy that I've read is a stack of dishes in a restaurant's buffet line. New plates are added at the top of stack and when a customer grabs one, the top-most plate is removed. Insert and delete operations are called &lt;em&gt;push&lt;/em&gt; and &lt;em&gt;pop&lt;/em&gt; respectively and both are performed in constant time O(1).
&lt;/p&gt;
&lt;p class="body"&gt;
When implementing a stack data structure, there are two main boundary conditions you need to account for: &lt;em&gt;underflow&lt;/em&gt; and &lt;em&gt;overflow&lt;/em&gt;. An &lt;em&gt;underflow&lt;/em&gt; occurs when an empty stack is "popped." This means that a delete operation was attempted on an empty stack. An &lt;em&gt;overflow&lt;/em&gt; occurs when a full stack is "pushed." This means that an insert operation was attempted on a full stack. Below, I have provided some pseudocode showing how a simple stack structure works:
&lt;/p&gt;
&lt;pre&gt;
void Push(int newValue)
{
    if (Stack isn't full (e.g. overflow))
    {
        - Add item to top of stack
        - Increment your top index value
    }
}

void Pop(int &amp; newValue)
{
    if (Stack isn't empty (e.g. underflow))
    {
        - Remove item from top of stack and assign
          to the newValue parameter
        - Decrement your top index value
    }
}
&lt;/pre&gt;
&lt;span class="fullpost"&gt;
&lt;strong&gt;&lt;u&gt;Queues&lt;/u&gt;&lt;/strong&gt;
&lt;p class="body"&gt;
A &lt;strong&gt;queue&lt;/strong&gt; is also a dynamic linear data structure with predetermined insertion and deletion operations. The main difference between a stack and queue is that a queue practices &lt;em&gt;FIFO&lt;/em&gt; ("&lt;strong&gt;F&lt;/strong&gt;irst &lt;strong&gt;I&lt;/strong&gt;n &lt;strong&gt;F&lt;/strong&gt;irst &lt;strong&gt;O&lt;/strong&gt;ut"). This means that new items are added at the top of the queue (or tail) and are removed from the bottom (or head). A good analogy is your standard waiting line to get into the movie theater. You get in line at the end and wait until those customers before you have purchased tickets and walked away. Then you get to go next while the people who entered the line after you await their turn. Insert and delete operations are called &lt;em&gt;enqueue&lt;/em&gt; and &lt;em&gt;dequeue&lt;/em&gt; respectively and both are performed in constant time O(1) just like stacks.
&lt;/p&gt;
&lt;p class="body"&gt;
Queues require slightly more work because we are required to keep up with both the beginning (the "head") and the ending (the "tail") of the structure in our implementations. With stacks, all we have to do is just make sure that the top-most element is within boundary limits. With queues, we are required to make sure that when an element is added, it goes in the tail's current location and when an item is removed, we have to make sure that the element in the head's current location is deleted. Also, the same boundary conditions in stacks exist for queues (e.g. &lt;em&gt;underflows&lt;/em&gt; and &lt;em&gt;overflows&lt;/em&gt;).  Below, I have provided some pseudocode showing how a simple queue structure works:
&lt;/p&gt;
&lt;pre&gt;
void Enqueue(int newVal)
{
    if (Queue isn't full (e.g. overflow))
    {
        - Add your value to the tail of the queue
        - Increment your tail index (or wrap it)
    }
}

void Dequeue(int &amp; newVal)
{
    if (Queue isn't empty (e.g. underflow))
    {
        - Remove item from queue and assign to the
          newVal parameter
        - Increment your head index (or wrap it)
    }
}
&lt;/pre&gt;
&lt;p class="body"&gt;
Stacks and queues are simple and easy to use for certain programming projects (e.g. postfix/infix evaluations). The easiest implementation technique used for both is to use an array as the internal structure (my pseudocode examples use an array). There are more complex implementations but arrays are used more frequently because of the simplicity. As always, post comments if something isn't clear and I'll try to help out.  If you'd like the full queue and stack class files (.h &amp; .cpp) let me know and I'll provide a link to them.  Until next time...
&lt;br&gt;&lt;br&gt;
-Gilemonster&lt;/p&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-115384634292115833?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/115384634292115833/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=115384634292115833&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115384634292115833'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115384634292115833'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/08/know-your-data-structures-queues-and.html' title='Know Your Data Structures:  Queues and Stacks'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-115388348004373405</id><published>2006-07-25T22:00:00.000-04:00</published><updated>2007-04-21T15:28:32.433-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Know Your C++:  Using Exceptions</title><content type='html'>&lt;p class="body"&gt;
As most of you already know, exceptions are errors or anomalies that occur during program execution. They are used as part of a programming philosophy that states, "You will not ignore this error scenario!" Rather than getting into why one would use exceptions, I am going to discuss a bit about their details and proper usage. The guts of C++ are always more interesting (right?).
&lt;/p&gt;
&lt;strong&gt;How They Work&lt;/strong&gt;
&lt;p class="body"&gt;
Lets begin with our standard throw invocation. In C++, the first thing performed is a copy of the exception object thrown is created. This copy is then "returned" from the function initiating the throw expression (the "throwing" function's scope is exited immediately and he is popped off the call stack). This process is called stack unwinding and will continue until an appropriate handler is found that can catch the object type thrown. As part of stack unwinding, each object that is popped off the stack goes out of scope, and therefore its destructor is called (this is good). This ensures that objects are cleaned up as they go out of scope (assuming the popped object's destructor does not throw an exception as well - more about this in a bit).
&lt;/p&gt;
&lt;p class="body"&gt;
If an appropriate exception handler is not found, the terminate() function is automatically invoked. By default, this calls the Standard C library function abort() which kills your application. As a side note, if an object's destructor throws an exception (nobody does that right?) terminate() is called as well.  Therefore, the general process goes as follows:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Function foo() throws an exception.&lt;/li&gt;
&lt;li&gt;That function and all objects local to it are destructed and popped of the call stack along with the foo() function itself.&lt;/li&gt;
&lt;li&gt;Then an appropriate handler is searched for all the way up the call stack until one (or none) is found.&lt;/li&gt;
&lt;li&gt;If this happens, terminate() is called which calls abort() and it sends your application packing.&lt;/li&gt;
&lt;/ol&gt;
&lt;strong&gt;Using Exceptions&lt;/strong&gt;
&lt;p class="body"&gt;
Now that we see the general idea of how they work, we need to make sure we account for various pitfalls in their use.  Because the proper use of exceptions is critical to an application's viability, it is imperative that we know these extra details.  Therefore, I have provided a few tips on how to use exceptions below.
&lt;/p&gt;
&lt;span class="fullpost"&gt;
&lt;strong&gt;Catch Exceptions by Reference&lt;/strong&gt;
&lt;p class="body"&gt;
In order to guarantee that all parts of your object are handled by a catch block, make sure that you catch your exceptions by reference. There are good reasons to do this. One, is that you avoid the normal overhead of an extra copy when the object is passed-by-value. Second, you ensure that any modifications provided to the exception object itself are preserved if the object needs to be re-thrown. Finally, you avoid the slicing of derived exception objects when base-class handlers catch them. Here is a quick sample of catching an exception by reference:
&lt;/p&gt;
&lt;pre&gt;
try
{
    ...
}
catch (MyException &amp; e)
{
    ...
}
&lt;/pre&gt;
&lt;strong&gt;Never Let Exceptions Leave an Object's Destructor&lt;/strong&gt;
&lt;p class="body"&gt;
We all hate memory leaks right?  Well in order to prevent memory leaks with exceptions, you have to first make sure that your destructors do not throw them.  For example, I have a class below, the &lt;span style="font-family:courier new;"&gt;MyLeakyClass&lt;/span&gt; class that is defined like this:
&lt;/p&gt;
&lt;pre&gt;
class MyLeakyClass
{
public:
    MyLeakyClass();
    ~MyLeakyClass();
    ...
private:
    wchar_t * szSimpleString1;
    wchar_t * szSimpleString2;
};

MyLeakyClass::MyLeakyClass()
{
    szSimpleString1 = new wchar_t[32];
    szSimpleString2 = new wchar_t[32];
}

MyLeakyClass::~MyLeakyClass()
{
    delete [] szSimpleString1;
    delete [] szSimpleString2;
}
&lt;/pre&gt;
&lt;p class="body"&gt;
What happens if the first delete call above generates an exception?  We know that execution stops immediately at the exception generating code and a matching exception handler is searched for by the caller (e.g. you called delete on an instance of &lt;span style="font-family:courier new;"&gt;MyLeakyClass&lt;/span&gt;).  The first thing to notice is that the &lt;span style="font-family:courier new;"&gt;szSimpleString2&lt;/span&gt; character array object is lost.  He never is deleted and therefore you have a leak of the 32 bytes.  Nice job, but it gets worse.  What if the calling code was not your invocation of the delete operator? If it was say, a part of the stack unwinding by another exception being generated, your destructor's exception (the second exception in this example) will result in a call to the &lt;span style="font-family:courier new;"&gt;terminate()&lt;/span&gt; function as we mentioned earlier.  Moreover, we know this means your application will most likely die.  Therefore, best-case scenario here, we leak if we have dynamically allocated objects on the heap.  Worst case is we leak and we die.  Not a good combination.  There is really only one solution to this problem if you do not want your application to die.  You need a try/catch all which does nothing.  This is the only way to guarantee that exceptions are not thrown from the handler and therefore no exceptions leave the destructor.  It is not pretty and some of you will disagree with it, but here is a simple example of &lt;span style="font-family:courier new;"&gt;MyLeakyClass&lt;/span&gt; destructor rewritten:
&lt;/p&gt;
&lt;pre&gt;
MyLeakyClass::~MyLeakyClass()
{
    try
    {
        delete [] szSimpleString1;
    }
    catch(...) {}

    try
    {
        delete [] szSimpleString2;
    }
    catch(...) {}
}
&lt;/pre&gt;
&lt;strong&gt;Catch exceptions in order of object inheritance&lt;/strong&gt;
&lt;p class="body"&gt;
When catching exceptions you have to understand that a handler will match the object type it is catches with the type of object being thrown. Like all objects in C++, a catch block which specifies a base class will match with a derived class object because of the is-a relationship. Therefore, you must order your catch blocks by the object hierarchy of the exception objects themselves.  For example, if you have three exception object types:
&lt;/p&gt;
&lt;pre&gt;
class Base {};
class Derived : public Base {};
class DerivedAgain : public Derived {};
&lt;/pre&gt;
&lt;p class="body"&gt;
you need to provide your catch blocks in the following order:
&lt;/p&gt;
&lt;pre&gt;
try
{
    ...
}
catch (DerivedAgain &amp; e)
{
    ...
}
catch (Derived &amp; e)
{
    ...
}
catch (Base &amp; e)
{
    ...
}
&lt;/pre&gt;
&lt;p class="body"&gt;
Starting with the most derived object and progressing up to the base-class, you are guaranteed to catch each and every type of the above three objects where appropriate. If you change that order, bad things can (and will) happen.  For example, if you swapped the order of the &lt;span style="font-family:courier new;"&gt;Base&lt;/span&gt; and &lt;span style="font-family:courier new;"&gt;Derived&lt;/span&gt; handlers, your &lt;span style="font-family:courier new;"&gt;Derived&lt;/span&gt; objects would never be caught (by the &lt;span style="font-family:courier new;"&gt;Derived&lt;/span&gt; handler) because they would always be caught by the &lt;span style="font-family:courier new;"&gt;Base&lt;/span&gt; handler.  This is because a &lt;span style="font-family:courier new;"&gt;Derived&lt;/span&gt; object is-a &lt;span style="font-family:courier new;"&gt;Base&lt;/span&gt; object.
&lt;/p&gt;
&lt;strong&gt;Avoid exception specifications&lt;/strong&gt;
&lt;p class="body"&gt;
Exception specifications are a mechanism that allows the programmer to declare the types (if any) of exceptions, a function will throw. In my opinion, they biggest benefit of using specifications is that it documents for a client/user what you throw. This is rather nice, but the adverse affect of using specifications greatly outweighs that benefit. The problem is when your function throws an exception that is not one of the specified types.  Here is an example.
&lt;/p&gt;
&lt;pre&gt;
// function declaration...
unsigned long FooBar() throw(int);

// function definition...
unsigned long FooBar()
{
    EvilExceptionThrower()    // Might throw anything
}
&lt;/pre&gt;
&lt;p class="body"&gt;
What happens if &lt;span style="font-family:courier new;"&gt;EvilExceptionThrower()&lt;/span&gt; throws an exception of type &lt;span style="font-family:courier new;"&gt;std::runtime_error&lt;/span&gt;?  &lt;span style="font-family:courier new;"&gt;FooBar()&lt;/span&gt; is defined to only throw exceptions of type int and therefore we enter the unknown.  Because our function isn't supposed to throw &lt;span style="font-family:courier new;"&gt;std::runtime_error&lt;/span&gt; exceptions, the default behavior is to call &lt;span style="font-family:courier new;"&gt;terminate()&lt;/span&gt;.  Oh yea, we know what happens next.  You just killed your application, congratulations. Now, if you still like the specifications and want to use them, you have one solution. Provide a catch all handler in your function that makes sure only specified exceptions are thrown (you could also pray that nothing called in your function throws non-specified exceptions). Depending on your design, this could be good or bad. In general, catch all handlers are not elegant in the general sense.  If you want your app to die, do not add the catch all.  If your application should try to continue on, add 'em.  In my opinion, it is preferable to add a comment in your function declaration, saying what type(s) of exceptions you throw. This way you do not limit your function and inadvertently kill your application.
&lt;/p&gt;
&lt;p class="body"&gt;
In general, exceptions are a effective and useful programming philosophy that I have used a number of times.  Like most things in C++, if used correctly and in the right circumstances, they perform their job well.  Until next time...
&lt;br&gt;&lt;br&gt;
- Gilemonster&lt;/p&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-115388348004373405?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/115388348004373405/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=115388348004373405&amp;isPopup=true' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115388348004373405'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115388348004373405'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/07/know-your-c-using-exceptions.html' title='Know Your C++:  Using Exceptions'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-115379269930607097</id><published>2006-07-24T20:37:00.000-04:00</published><updated>2007-04-21T15:28:32.433-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Know Your C++: The new operator and operator new</title><content type='html'>&lt;p class="body"&gt;
Make sure you know how the new operator works when you use it in your C++ programs. Here is an example of how it is normally used:
&lt;/p&gt;
&lt;pre&gt;
wchar_t * myString = new wchar_t[256];
&lt;/pre&gt;
&lt;p class="body"&gt;
Most C++ programmers are familiar with this call and will tell you that the &lt;em&gt;new operator&lt;/em&gt; invokes the target object&amp;#44s constructor. That constructor performs operations like initializing member variables and whatnot. Yes, this is true, but how is this memory allocated and who allocates it?
&lt;/p&gt;
&lt;p class="body"&gt;
This task is performed by a call to &lt;em&gt;operator new&lt;/em&gt; (could the names be more confusing?). You can think of this as like a call to &lt;em&gt;malloc()&lt;/em&gt;. &lt;em&gt;operator new&lt;/em&gt; is usually declared like this:
&lt;/p&gt;
&lt;pre&gt;
void * operator new(size_t size);
&lt;/pre&gt;
&lt;p class="body"&gt;
The return type is &lt;em&gt;void*&lt;/em&gt; because it returns a pointer to raw, uninitialized memory (on the heap or free store). You will also notice that the &lt;em&gt;size_t&lt;/em&gt; parameter actually tells the routine how much memory to allocate. In the case where &lt;em&gt;operator new&lt;/em&gt; cannot allocate the desired size, it will either return NULL or throw an exception. Now that we know who actually allocates the memory for the new operator, let us look at how that memory is allocated.
&lt;/p&gt;
&lt;p class="body"&gt;
When a heap allocation request is invoked, a scan is performed that looks for a sufficiently large chunk of contiguous memory. This entails traversing the heap through pointers that point to the next areas on the heap that contain free memory blocks. When a sufficiently sized block is found, the memory is &amp;#34tagged&amp;#34 with a size value (the boundary of where this allocated chunk ends) and pointers are rearranged so that this memory block is not seen as &amp;#34free&amp;#34 (until we delete it later). Finally, a pointer to the starting address of this newly allocated section on the heap is then returned to the caller of &lt;em&gt;operator new&lt;/em&gt; (in our case that is the &lt;em&gt;new operator).&lt;/em&gt;
&lt;/p&gt;
&lt;p class="body"&gt;
Now that our starting memory address is returned we can continue with the last task that the &lt;em&gt;new operator&lt;/em&gt; must perform. This final step is the initialization of the allocated memory via invocation of the target object&amp;#39s constructor.
&lt;/p&gt;
&lt;p class="body"&gt;
When a program is finished with its dynamically allocated memory, it must be manually released by invoking the &lt;em&gt;delete operator&lt;/em&gt;. As with the &lt;em&gt;new operator&lt;/em&gt;, a similar process occurs when &lt;em&gt;operator delete&lt;/em&gt; is called by the &lt;em&gt;delete operator&lt;/em&gt; (yes, this naming is just as confusing as with &lt;em&gt;new&lt;/em&gt;). When this occurs, the deallocated memory is added back to the top of the heap so it can be reused.
&lt;/p&gt;
&lt;p class="body"&gt;
To summarize, we can see that a call to the &lt;em&gt;new operator&lt;/em&gt;, always performs the following two operations:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Call the &lt;em&gt;operator new&lt;/em&gt; function which returns a pointer to the starting address of an uninitialized memory block on the heap, and&lt;/li&gt;
&lt;li&gt;Call the target object&amp;#39s constructor to initialize that memory block.&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="body"&gt;
Knowing this type of information is a must for C++ programmers. Even though you may never need to overload &lt;em&gt;operator new&lt;/em&gt; (you can&amp;#44t override the &lt;em&gt;new operator&lt;/em&gt;) it is useful information for understanding how C++ allocates and instantiates user-defined objects.
&lt;br&gt;&lt;br&gt;
-Gilemonster&lt;/p&gt;
&lt;p class="body"&gt;
** Update **&lt;br&gt;
There are a couple more items to mention that have come from comments and other readers.
&lt;ul&gt;
&lt;li&gt;First of all when creating an array of objects, the &lt;i&gt;new operator&lt;/i&gt; actually invokes &lt;i&gt;operator new[]&lt;/i&gt;.  As Chris added below, this is commonly known as &lt;i&gt;array new&lt;/i&gt; which further confuses programmers.&lt;/li&gt;
&lt;li&gt;Second, the &lt;i&gt;new operator&lt;/i&gt; doesn't always allocate memory via &lt;i&gt;operator new&lt;/i&gt; if &lt;i&gt;placement new&lt;/i&gt; is invoked instead.  You can override &lt;i&gt;operator new&lt;/i&gt; with an additional void* parameter that is a block of memory that has already been allocated.  This allows the programmer to provide a block of memory for reuse and therefore not perform the standard allocation that the object requires.&lt;/li&gt;
&lt;/ul&gt;
** End Update **&lt;/p&gt;&lt;em&gt;&lt;/em&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-115379269930607097?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/115379269930607097/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=115379269930607097&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115379269930607097'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115379269930607097'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/07/know-your-c-new-operator-and-operator.html' title='Know Your C++: The new operator and operator new'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-115371068667442831</id><published>2006-07-23T19:18:00.000-04:00</published><updated>2007-04-21T15:31:12.590-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='General'/><title type='text'>Know Your Data Structures:  Hash Tables</title><content type='html'>&lt;p class="body"&gt;
A &lt;strong&gt;Hash table&lt;/strong&gt; is a data structure that associates &lt;em&gt;keys&lt;/em&gt; to &lt;em&gt;values&lt;/em&gt; (e.g. dictionary-like objects). It takes a &lt;em&gt;key&lt;/em&gt; and maps that to an internally stored &lt;em&gt;value&lt;/em&gt;. The mapping of the &lt;em&gt;key&lt;/em&gt; to its location in the hash table is done via a &lt;em&gt;hashing function&lt;/em&gt;. The hashing function attempts to transform a &lt;em&gt;key&lt;/em&gt; into a unique location in the hash table. If this can be performed, insertions, deletions, and searches can be performed in O(1) time. This is because you are basically using direct addressing into the hash table's "array of values." This is similar to indexing a value in an array. When an array element is accessed, it is done in O(1) because you know the exact offset into the data structure (e.g. myarray[5]). You don't have to waste processing time searching for the key's matching value by traversing through the data structure (e.g. as in a linked list). Click 
&lt;a href="http://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/HASHTB08.svg/744px-HASHTB08.svg.png"&gt;here&lt;/a&gt; for a simple diagram which displays the internal structure of a hash table.
&lt;/p&gt;
&lt;p class="body"&gt;
The problem with hash tables is when the hashing function cannot transform a key to a unique location in the hash table (e.g. two keys &lt;em&gt;hash&lt;/em&gt; to the same hash table index). This is called a &lt;em&gt;collision&lt;/em&gt; and there are a number of techniques are used to solve this problem. The two main techniques I will discuss here are called &lt;em&gt;chaining&lt;/em&gt; and &lt;em&gt;open addressing&lt;/em&gt;.
&lt;/p&gt;
&lt;strong&gt;Chaining&lt;/strong&gt;
&lt;p class="body"&gt;
Chaining basically uses a linked list as the structure to hold all the records that collide at the same index. When performing operations with a hash table that implements chaining, extra code is required to perform a second step in order to access, modify, or delete a key/value pair. This second step is the traversal of this "collided linked list" in order to find the appropriate location where an object can be accessed, modified, or deleted.
&lt;/p&gt;
&lt;p class="body"&gt;
Of course there are advantages and disadvantages of using &lt;em&gt;chaining&lt;/em&gt; as a collision resolution technique. Because we are operating on a linked list, we get the benefit of deletions being simple and quick (pointer reassignment). Unfortunately, we also inherit the disadvantages of standard linked list overhead and that traversal takes longer than with direct addressing.
&lt;/p&gt;
&lt;strong&gt;Open Addressing&lt;/strong&gt;
&lt;p class="body"&gt;
Open addressing involves actually storing the hashed index records within the internal hash table array. Collision is resolved through &lt;em&gt;probing&lt;/em&gt;, which is the searching of alternate locations in the array. If an empty array slot is found, this signifies that there is no such key in the table. The main problem with open addressing is when the slots in the value array begin to fill up (called&lt;em&gt; &lt;/em&gt;the &lt;em&gt;load factor&lt;/em&gt;). As this increases, probing because expensive and can incur a large time cost. As a general rule, 80% load factor is about the time when open addressing becomes too expensive to use.
&lt;/p&gt;
&lt;span class="fullpost"&gt;
&lt;strong&gt;Know When to Use Hash Tables...&lt;/strong&gt;
&lt;ul&gt;
&lt;li&gt;Hash tables are not the best solution for ordered data sets. Remember that hash tables store their values in pseudo-random locations and therefore accessing ordered data sets can be time intensive.&lt;/li&gt;
&lt;li&gt;Since hash tables can be time intensive in worst-case scenarios it is best to just use a simple array indexing structure if possible. They are usually faster.&lt;/li&gt;
&lt;/ul&gt;
&lt;strong&gt;Performance&lt;/strong&gt;
&lt;ul&gt;
&lt;li&gt;On average, hash table operations can be performed in O(1) time.&lt;/li&gt;
&lt;li&gt;Worst-case, hash table operations can be performed in O(n) time.&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="body"&gt;
In general, I hope you can see that hash tables are an interesting data structure when used appropriately. They have the capability of providing O(1) time operations which is extremely nice in "dictionary-like" objects that contain a large number of records that need to be stored. But take care when using them by verifying that the hashing function is well written. This function is the single most important component to providing good hash table performance. Until next time...
&lt;br&gt;&lt;br&gt;-Gilemonster&lt;/p&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-115371068667442831?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/115371068667442831/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=115371068667442831&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115371068667442831'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115371068667442831'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/07/know-your-data-structures-hash-tables.html' title='Know Your Data Structures:  Hash Tables'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-115033802828122905</id><published>2006-06-14T21:10:00.000-04:00</published><updated>2007-04-21T15:28:32.433-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Discussion Topic #3:  STL Containers and Object Destruction</title><content type='html'>&lt;p class="body"&gt;
When using STL containers, be aware that they assume they hold value-like objects. One of the pitfalls with this is that during container destruction it assumes that the objects it holds are being fully destructed as well. If your container holds a collection of raw pointers to user-defined objects, this is not the case. The memory each raw pointer points to is actually not destructed unless you manually delete the raw pointer itself. The STL does &lt;span style="FONT-WEIGHT: bold"&gt;not&lt;/span&gt; do this for you. To help prevent this type of design flaw, here are a few guidelines to use.
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;If a container owns the objects it holds, use either full object types (e.g. vector&amp;lt;foo&amp;gt;) or reference-counted smart pointers to those objects (e.g. vector&amp;lt; shared_ptr&amp;lt;foo&amp;gt; &amp;gt;).
&lt;/li&gt;
&lt;li&gt;If a container does not own the objects it holds, the use of raw pointers is okay (e.g. vector&amp;lt;foo*&amp;gt;).&lt;/li&gt;
&lt;li&gt;In general, &lt;span style="FONT-STYLE: italic"&gt;never&lt;/span&gt; use containers of &lt;span style="FONT-STYLE: italic"&gt;auto_ptr&lt;/span&gt; (e.g. vector&amp;lt; auto_ptr&amp;lt;foo&amp;gt; &amp;gt;).&lt;/li&gt;
&lt;/ol&gt;
&lt;p class="body"&gt;
Now these are just guidelines and therefore there are exceptions. Here are a few examples.
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;You have performance and/or space-critical requirements that make the use of containers of raw pointers more attractive. This is perfectly valid, but always be aware that you are required to manually delete those pointers before destructing your container.&lt;/li&gt;
&lt;li&gt;The copy constructor of your object might be really expensive and therefore raw pointers to those objects might be held in the container.&lt;/li&gt;
&lt;li&gt;You write have a container object that was written to specifically work with &lt;span style="FONT-STYLE: italic"&gt;auto_ptr&lt;/span&gt; (sounds like suicide, but it might be legitimate).&lt;/li&gt;
&lt;/ol&gt;
&lt;p class="body"&gt;
In general, it is probably better to just use reference-counted smart pointers because you then never have to worry about whether you own the object or not. If you do own it, then your count should drop to zero on container destruction and no memory is leaked. Also, if you don't own the objects in your container, then a reference-counted smart pointer merely increments the reference count and decrements it during container construction and destruction respectively. You therefore do not destruct the objects unless you are the last person using them. For more information on reference-counted smart pointers, take a look at &lt;a href="http://boost.org/libs/smart_ptr/shared_ptr.htm"&gt;&lt;span style="FONT-STYLE: italic"&gt;shared_ptr&lt;/span&gt;&lt;/a&gt;. This is a new STL smart pointer from &lt;span style="FONT-STYLE: italic"&gt;Boost&lt;/span&gt; that can prove to be very useful in certain situations.
&lt;br&gt;&lt;br&gt;
-Gilemonster&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-115033802828122905?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/115033802828122905/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=115033802828122905&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115033802828122905'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/115033802828122905'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/06/discussion-topic-3-stl-containers-and.html' title='Discussion Topic #3:  STL Containers and Object Destruction'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-114868227024226546</id><published>2006-05-26T18:24:00.000-04:00</published><updated>2007-04-21T15:31:12.590-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='General'/><title type='text'>.bat file continuation character</title><content type='html'>I've finally found the continuation character for continuing a line in a bat file.  It is the caret "^".&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-114868227024226546?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/114868227024226546/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=114868227024226546&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114868227024226546'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114868227024226546'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/05/bat-file-continuation-character.html' title='.bat file continuation character'/><author><name>tac</name><uri>http://www.blogger.com/profile/08182934834057645927</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='09326619486242134333'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-114781799077683110</id><published>2006-05-16T18:18:00.000-04:00</published><updated>2007-04-21T15:29:00.028-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Site News'/><title type='text'>New mailing list added to notify readers of new posts</title><content type='html'>&lt;p class="body"&gt;
I just added a new mailing list for those people who wish to be updated when a contributor posts a new discussion topic. If you wish to be added to this mailing list (&lt;span style="font-style: italic;"&gt;GilemonsterBlog@googlegroups.com&lt;/span&gt;), send me an &lt;a href="mailto:Gilemonster@gmail.com"&gt;email&lt;/a&gt; along with your email address and I'll add you to the group.
&lt;br&gt;&lt;br&gt;
-Gilemonster&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-114781799077683110?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/114781799077683110/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=114781799077683110&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114781799077683110'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114781799077683110'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/05/new-mailing-list-added-to-notify.html' title='New mailing list added to notify readers of new posts'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-114780817168674723</id><published>2006-05-16T15:31:00.000-04:00</published><updated>2007-04-21T15:31:12.590-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='General'/><title type='text'>Should architects code?</title><content type='html'>&lt;p class="body"&gt;
This is always an interesting discussion to me (since I am an architect). I just saw this &lt;a href="http://www.ddj.com/blog/architectblog/archives/2006/05/should_architec_1.html"&gt;article&lt;/a&gt; on this topic in Dr. Dobb's.
&lt;/p&gt;
&lt;p class="body"&gt;
Personally, I think architects should be keep their fingers in the code to some extent. I just think it's difficult to architect/design a system if you don't know how it will be built. I don't write as much code as I used to, but I still like to stay involved and even participate in some coding and detailed design exercises from time to time.
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-114780817168674723?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/114780817168674723/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=114780817168674723&amp;isPopup=true' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114780817168674723'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114780817168674723'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/05/should-architects-code.html' title='Should architects code?'/><author><name>TigerEagle</name><uri>http://www.blogger.com/profile/08382291084455087444</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='14432520922044303941'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-114774817349517230</id><published>2006-05-15T20:48:00.000-04:00</published><updated>2007-04-21T15:28:32.434-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Discussion Topic #2:  Create standalone and "guarded" header files</title><content type='html'>&lt;p class="body"&gt;
When writing C++ header files, you should always be conscious that your header files can be included by other projects and files. The reason for doing this is because improperly written header files can cause a number of problems including stray dependencies, unnecessary include burdens on your header file's users, and multiple inclusion/redefinitions to name a few. Two techniques that help to prevent this are making your header files standalone and using include guards. Both techniques are described below.
&lt;/p&gt;
&lt;strong&gt;Make Your Headers Self-Sufficient&lt;/strong&gt;
&lt;p class="body"&gt;
Header files should be written so that they can stand on their own two feet. Header files that include other unneeded header files can cause stray dependencies and longer build times (because the compiler is required to parse each header file that is included at compile time). The first step in making your header files self-sufficient is to look at each header file it includes and then verify that it actually needs to include that file. This is easily verifiable by just commenting out the included file and then recompiling. If the compile fails, at least that included object's type is needed. If the compile works, you can delete the commented out include altogether. Once you have verified which includes are required, the second step is determine what objects in those header files are actually needed. If you do not need the included object's definition (i.e. You return it from a function, it is declared as a parameter in one of your functions, etc) you can forgo including the type's definition in your header. You can achieve this with a &lt;span style="FONT-STYLE: italic"&gt;forward declaration&lt;/span&gt;. A forward declaration allows you to declare the use of a type without the details of its definition. Note: The only time you need the type's definition in your header is when the compiler needs to know the size of the type (i.e. your have the included object as a member of your class) or when you need to use/call a member of that type (i.e. you invoke a function on the included object). Here is a sample header that shows displays forward declares and also minimal include directives:
&lt;/p&gt;
&lt;pre&gt;
#include &amp;lt;atlbase.h&amp;gt;    // include header for VARIANT class member

class SnmpRequestResults; // forward declaration of results class

class SnmpRequest
{
public:
    SnmpRequest();
    ~SnmpRequest();
    SnmpRequestResults* GetResults();

private:
    VARIANT m_vDataType;
};
&lt;/pre&gt;
&lt;p class="body"&gt;
As you can see in the above SnmpRequest class, we use both the forward declaration and a small number of include directives (we only include atlbase.h). We have removed the need for including the SnmpRequestResults header in our header and therefore made our own header file more self-sufficient. When using these techniques, think of your header files as being used completely by itself.
&lt;/p&gt;
&lt;strong&gt;Use #include Guards&lt;/strong&gt;
&lt;p class="body"&gt;
Make sure that your header files are only &lt;span style="FONT-STYLE: italic"&gt;defined&lt;/span&gt; once in case it is included multiple times. You can guarantee this with the use of include guards. Modern compilers recognize these guards at the top of header files and therefore prevent multiple inclusions of a header file during the compilation of a single cpp file. They are implemented with preprocessor directives. The guards need to conform to the following rules:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The name needs to be unique.&lt;/li&gt;
&lt;li&gt;No code or comments should come before or after the guarded portion.&lt;/li&gt;
&lt;li&gt;The guards should wrap the entire object declaration.&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="body"&gt;
Here is an example of include guard use:
&lt;/p&gt;
&lt;pre&gt;
#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED

class Foo
{
public:
    Foo();
    ~Foo();
    int ComputeFooSize();
};
#endif
&lt;/pre&gt;
&lt;p class="body"&gt;
By using include guards and making header files self-sufficient, you can make your header files lightweight and therefore easier to use by other code. It also has the indirect affect of you having to write less code. That's always good. I hope this was helpful and if there are any questions, post away.
&lt;br&gt;&lt;br&gt;
- Gilemonster&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-114774817349517230?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/114774817349517230/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=114774817349517230&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114774817349517230'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114774817349517230'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/05/discussion-topic-2-create-standalone.html' title='Discussion Topic #2:  Create standalone and &quot;guarded&quot; header files'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-114744464949767773</id><published>2006-05-12T10:36:00.000-04:00</published><updated>2006-08-08T21:18:50.980-04:00</updated><title type='text'>Visual Studio Code Analysis Tools?</title><content type='html'>&lt;p class="body"&gt;
Has anyone used the new code analysis tools builtin to Visusal C++ 2005?  What do you think about the features?  Do the tools find relevant bugs?
&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-114744464949767773?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/114744464949767773/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=114744464949767773&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114744464949767773'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114744464949767773'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/05/visual-studio-code-analysis-tools.html' title='Visual Studio Code Analysis Tools?'/><author><name>TigerEagle</name><uri>http://www.blogger.com/profile/08382291084455087444</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='14432520922044303941'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-114701681212705255</id><published>2006-05-07T11:44:00.000-04:00</published><updated>2007-04-21T15:28:32.434-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Discussion Topic #1:  Logical vs. Bitwise constness</title><content type='html'>&lt;p class="body"&gt;
One of my favorite C++ programming tips is the use of &lt;strong&gt;const&lt;/strong&gt; as a semantic constraint. I use it whenever and wherever I can because it can significantly reduce logic errors and turn them into compile errors (a good thing).  In order to use it properly, you need to know how C++ defines constness.  There are two types of object constness in the C++ world and they affect class design in different ways.
&lt;/p&gt;
&lt;p class="body"&gt;
C++ compilers, by default, support the use of &lt;em&gt;bitwise constness&lt;/em&gt;. This means that no part of an object can be modified after instantiation when declared with the const modifier.  Inside a class definition, this is great for "getter" functions that merely return values to the caller. By declaring the functions &lt;strong&gt;const&lt;/strong&gt;, you are telling the caller (and the compiler) that this member function cannot modify any members of the class it is working on.  Here's an example:
&lt;/p&gt;
&lt;pre&gt;
class MyObject
{
public:
    MyObject();  // constructor
    ~MyObject(); // destructor

    long GetObjectID() &lt;strong&gt;const&lt;/strong&gt;;
    void SetObjectID(long lngID);

    long GetObjectLength() &lt;strong&gt;const&lt;/strong&gt;;
    void SetObjectLength(long lngLength);

private:
    long m_lngID;
    long m_lngLength;
};
&lt;/pre&gt;
&lt;p class="body"&gt;
In the above example, you will notice that there are two class functions that are defined with the &lt;strong&gt;const&lt;/strong&gt; modifier.  This tells the compiler that the function will not modify either the &lt;i&gt;m_lngID&lt;/i&gt; or &lt;i&gt;m_lngLength&lt;/i&gt; class members.  So, by default, the definitions of the two "get" functions above cannot contain code that changes those two private class members.  Here's a sample function definition:
&lt;/p&gt;
&lt;pre&gt;
long MyObject::GetObjectID() &lt;strong&gt;const&lt;/strong&gt;
{
    m_lngID = 25;       // &lt;strong&gt;ERROR&lt;/strong&gt;!
    m_lngLength = 0;    // &lt;strong&gt;ERROR&lt;/strong&gt;!
    return m_lngID;     // Allowed!
}
&lt;/pre&gt;
&lt;p class="body"&gt;
Above you will note that attempts to assign values to &lt;em&gt;m_lngID&lt;/em&gt; and &lt;em&gt;m_lngLength&lt;/em&gt; will cause the compiler to generate an error.  Alternatively, the return statement will not generate an error b/c it is merely returning a copy of one of the class' data members.  Its not changing it.
&lt;/p&gt;
&lt;p class="body"&gt;
Now sometimes you need a &lt;strong&gt;const&lt;/strong&gt; function that guarantees it won't change certain class members, but might change others.  This brings about the idea of &lt;strong&gt;logical constness&lt;/strong&gt;. Let's say you have a class member who's value can be changed (and that not affect your object's definition of constness). In C++ you can declare this member with the keyword &lt;strong&gt;mutable&lt;/strong&gt;. This can be useful at times. Scott Meyers suggests that when designing interfaces, you should use logical constness. He makes a good point b/c &lt;strong&gt;mutable&lt;/strong&gt; gives the designer the ability to create his/her own definition of what constness means for a particular object.  Example below:
&lt;/p&gt;
&lt;pre&gt;
class MyObject
{
public:
    MyObject();  // constructor
    ~MyObject(); // destructor

    long GetObjectID() &lt;strong&gt;const&lt;/strong&gt;;
    void SetObjectID(long lngID);

    long GetObjectLength() &lt;strong&gt;const&lt;/strong&gt;;
    void SetObjectLength(long lngLength);

private:
    &lt;strong&gt;mutable &lt;/strong&gt;long m_lngID;
    long m_lngLength;
};
&lt;/pre&gt;
&lt;p class="body"&gt;
The above class mirrors our earlier example in all aspects except that the &lt;em&gt;m_lngID&lt;/em&gt; member is declared with the mutable modifier.  This tells the compiler to allow modifications to this member inside of const class functions.  Here's a sample function definition:
&lt;/p&gt;
&lt;pre&gt;
long MyObject::GetObjectID() &lt;strong&gt;const&lt;/strong&gt;
{
    m_lngID = 25;    // &lt;strong&gt;Allowed&lt;/strong&gt; b/c the member mutable
    m_lngLength = 0; // &lt;strong&gt;ERROR&lt;/strong&gt;!
    return m_lngID;  // &lt;strong&gt;Allowed&lt;/strong&gt;!
}
&lt;/pre&gt;
&lt;p class="body"&gt;
The above function definition shows how the compiler will treat both member variables based on whether they where declared using mutable.
&lt;/p&gt;
&lt;p class="body"&gt;
So, from the examples above you can see how using &lt;strong&gt;const&lt;/strong&gt; as a semantic constraint can be useful.  The examples above also show how mutable allows the designer to define what constness means for a particular object.  There is one final note to this topic and that is &lt;strong&gt;const&lt;/strong&gt; modifiers aren't "full-proof" in their protection of class member modification.  Let's add a new routine to our &lt;strong&gt;MyObject&lt;/strong&gt; class that returns a pointer to a character string:
&lt;/p&gt;
&lt;pre&gt;
class MyObject
{
public:
    // Constructor, destructor, blah blah...

    &lt;strong&gt;char *&lt;/strong&gt; GetObjectName() &lt;strong&gt;const&lt;/strong&gt;;

private:
    char * m_strObjectName;
};

// Defintion
&lt;strong&gt;char *&lt;/strong&gt; MyObject::GetObjectName() &lt;strong&gt;const&lt;/strong&gt;
{
    return m_strObjectName;
}
&lt;/pre&gt;
&lt;p class="body"&gt;
The &lt;strong&gt;GetObjectName()&lt;/strong&gt; function is declared as a const function, but the private &lt;em&gt;m_strObjectName&lt;/em&gt; variable isn't safe from modification!  How can that be you say?  The reason is because the function is returning a pointer to the class' data member.  Anyone can now take that pointer and do with it what they wish.  Here's the correct way to declare the above routine and ensure the name variable isn't changed:
&lt;/p&gt;
&lt;pre&gt;
&lt;strong&gt;const&lt;/strong&gt; char * GetObjectName() &lt;strong&gt;const&lt;/strong&gt;;
&lt;/pre&gt;
&lt;p class="body"&gt;
This states that we aren't going to change m_strObjectName in the function and also that we are returning a pointer to a constant character string.  The string that the pointer "points" to cannot be changed.  This now guarantees that the caller can only query the value of the class' name member.
&lt;/p&gt;
&lt;p class="body"&gt;
I hope this wasn't too confusing.  If so, let me know and I'll attempt to further  demonstrates the idea.  The bottom line is that using const forces code semantics that improve code stability.  Understanding how C++ defines constness also allows the designer to provide more customized object definitions.
&lt;br&gt;&lt;br&gt;
- Gilemonster&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-114701681212705255?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/114701681212705255/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=114701681212705255&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114701681212705255'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114701681212705255'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/05/discussion-topic-1-logical-vs-bitwise.html' title='Discussion Topic #1:  Logical vs. Bitwise constness'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-27397864.post-114679767778257602</id><published>2006-05-04T22:47:00.000-04:00</published><updated>2007-04-21T15:28:32.434-04:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C++'/><title type='text'>Recommended C++/STL Reading</title><content type='html'>&lt;p class="body"&gt;
I've read a number of articles/books on general C++ programming and have created my own personal list of books that are a requirement in your own cube.  It is my opinion that anything Scott Meyers writes is worth reading.  They are always informative and interesting.
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;em&gt;Effective C++&lt;/em&gt; (3rd ed.)&lt;/li&gt;
&lt;li&gt;&lt;em&gt;More Effective C++&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Effective STL&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p class="body"&gt;
They are great to keep around if you are like me and can't remember all the topics you've read in the past.  Others?
&lt;br&gt;&lt;br&gt;
-Gilemonster&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/27397864-114679767778257602?l=writebettercode.org%2Findex.html' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/114679767778257602/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=27397864&amp;postID=114679767778257602&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114679767778257602'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/27397864/posts/default/114679767778257602'/><link rel='alternate' type='text/html' href='http://writebettercode.org/2006/05/recommended-cstl-reading.html' title='Recommended C++/STL Reading'/><author><name>Gilemonster</name><uri>http://www.blogger.com/profile/15933947108501953190</uri><email>noreply@blogger.com</email><gd:extendedProperty xmlns:gd='http://schemas.google.com/g/2005' name='OpenSocialUserId' value='17521078200872923466'/></author><thr:total xmlns:thr='http://purl.org/syndication/thread/1.0'>2</thr:total></entry></feed>