Monthly Archives: August 2009

Different ways to iterate over a vector

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).

Continue reading Different ways to iterate over a vector

Nuances of exception rethrow

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.

Continue reading Nuances of exception rethrow

Pure virtual destructor

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?

Continue reading Pure virtual destructor