Complexity of std::list::size() is... O(N)

I want to share my recent "discovery" that was very shocking to me. Reading comments to a slashdot story about the C++0x standard I read something very interesting: std::list::size() has O(N) complexity in the gcc compiler.

Not so obvious multi-thread programming specific bugs.

We all know that when writing multi-threaded programs one should remember about few more details like locking, using thread-safe libraries etc. Here is a list of not-so obvious bugs specific to multi-threaded programs. Many of them are not mentioned in documentation or tutorials for beginners, but I think everybody who is using threads will hit them eventually.

Threads and fork(): think twice before mixing them.

When debugging a program I came across a bug that was caused by using fork(2) in a multi-threaded program. I thought it's worth to write some words about mixing POSIX threads with fork(2) because there are non-obvious problems when doing that.

Using Valgrind to debug memory leaks

Valgrind is a wonderful tool useful mainly to debug memory related problems in C/C++ programs. I don't know a better tool to find memory leaks. Although output of this program is often clear and intuitive it's worth to spend some time to get deeper knowledge of how Valgrind works, what exactly its messages mean and what are the problematic cases when tracing a memory leak is harder even with Valgrind.

C++ exception specifications are evil

When I began to program in C++ I was already experienced in C and had written some code in Java. After writing few thousands lines of code in this language I felt comfortable with all of it's goodies like templates, inheritance, operator overloading and (I thought so) exceptions. But I made at least one mistake: I used exception specifications. My intention was to use them as in Java: tell the compiler that this method throws specific exceptions so it can use this information to optimize code and tell me when I'm throwing/catching wrong exceptions. A great surprise was that in practice in most cases writing exception specifications slows the code and introduces bugs!

C++ object's reference counting

Last update: 13.01.2009

Passing objects to methods by pointer or reference is very handy if you want to boost performance by avoiding invoking the copy constructor. Sometimes it's the only way to pass an object because it doesn't have a copy constructor or assignment operator defined. An example would be an object that has an open operating system resource that can't be safely shared.

Let's say that you are creating a class that does some low-level operation on a file. It contains a file descriptor as a field:

  1. class LowLevelFile
  2. {
  3. int fd
  5. // [...]
  6. };

Syndicate content