cplusplus.co.il

Archive for August 2009

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 »

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 »

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 »

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 decleration statements.

Read the rest of this entry »

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 »

Today, a somewhat basic post.

Suppose you have a multi-dimensional array and would like to pass it to a function, but still be able to access it easily (by using row,col tuples for instance): passing the pointer is probably not the right way to go (although you could cast inside, but that’s ugly).

Read the rest of this entry »

The classes istringstream & ostringstream can be utilized to create generic, templated, toString() & fromString() functions. This functionality (which is built-in in many languages, such as Java) may come in very handy, quite often.

Read the rest of this entry »