Different ways to iterate over a vector

August 28th, 2009 § 10 Comments

Iterating over a vector is a pretty simple task we get to do pretty often. It can be achieved in quite a few ways:

  • Using normal random access (operator[] with index).
  • Using std::iterator.
  • Using std::for_each algorithm.

I set out to check the runtime differences between all these options, and the results turned out to be a little surprising (or not).

« Read the rest of this entry »

Nuances of exception rethrow

August 23rd, 2009 § Leave a Comment

When you throw an exception, the thrown object is copied to a special location in the memory. Now, suppose you wanted to catch an exception (by reference ofcourse), alter it slightly, and then rethrow it with hope that the same object would be rethrown. The language provides two ways to do just that, which are very different in what they actually do below the surface.

« Read the rest of this entry »

Pure virtual destructor

August 22nd, 2009 § 2 Comments

Sometimes you would like to create an abstract class, but there is no method you could naturally declare as pure virtual (=0) in order to achieve that (in a tag interface, for example).

In such cases the destructor may be the perfect candidate: as it should always be declared virtual if inheritance is considered, it may as well be pure virtual.

But then we have a hazard on our hands - since destructor (and constructor) invocation in inheriting classes is recursive, we will end up with a pure virtual method call - with no suitable code to execute. How do we solve this issue?

« Read the rest of this entry »

Problematic declaration syntax

August 20th, 2009 § 2 Comments

This question was written by a friend who luckily let me use it. It presents a very common pitfall of C++, regarding the syntax of declaration statements.

« Read the rest of this entry »

Portable measurement of execution time

August 19th, 2009 § 2 Comments

Once in a while so it happens that a programmer wishes to time his own creation. This article presents a simple and portable implementation of a Timer class which saves the time of its creation and computes the time it took until destruction, effectively measuring the runtime spent in the enclosing scope.

« Read the rest of this entry »

Where Am I?

You are currently viewing the archives for August, 2009 at 0x.