Want speed? Don’t (always) pass by value.

As the title indicates, this post is motivated by Dave Abrahams’ influential blog post “Want speed? Pass by Value”. In that post, Abrahams makes the case that often passing and returning by value is cheaper than passing by reference, or trying to engineer some means to return pointers or references. This is due to copy elision, which has been a part of the language since standardization, and move semantics, which were introduced with C++11. Often, passing and returning by value results in code that is both clearer and safer. This in itself is a compelling argument, speed considerations aside.

(more…)

Concurrent queue – C++11

This is an implementation of the classic multiple producer, multiple consumer thread-safe queue concept. Much has been said about this before, but I need a simple, pure C++ version of this for future posts, so I thought I might as well say a few words about it. I had set a variant on this theme as an exercise in a C++11 workshop, and I also encountered a simplified variant of it in a job interview assessment question. It asked to implement a thread safe queue a single producer and a single consumer thread. The interface was minimal and clean:

template <typename T>
struct Queue
{
  // pop an element and return a copy. Block if queue empty.
  T pop();
  //  push an element to the back of the queue.
  void push(const T& item);
};

(more…)

Simple observer pattern – C++11

This is an implementation of a simple observer pattern, using only C++ standard library facilities. It makes use of C++11 polymorphic function objects and formed the basis of an exercise I set for an introductory C++11 workshop given at work. We shall develop simple code elements to be used something like this:

int main()
{
  Subject s;
  Observer o1 = ....;
  Observer o2 = ....;
  Observer o3 = ....;

  s.registerObserver(EventA, o1);
  s.registerObserver(EventB, o3);
  s.registerObserver(EventD, o1);
  s.registerObserver(EventB, o2);
  s.registerObserver(EventC, o3);

  s.notify(EventB); // notify all observers registered for EventB
  s.notify(EventC); // notify all observers registered for EventC
}

(more…)