Blog Posts

Programming to interface is a fairly good programming practice. It allows decoupling of classes, as stated in the Dependency Inversion Principle, as well as easy testing in context of Test-driven developpement. Stricly speaking, there is no interface in C++. Instead, we use inheritance from a base class with no data member and all its member functions marked as public, pure and virtual1. But calling virtual functions doesn’t come for free, we need to pay the cost of : making an indirect call through the vtable, branch (mis)prediction, instruction cache miss, … Should we pay this cost just because we want to do things right ? As we will see in this post, in some cases we could get rid of this price using the power of Devirtualization.

  1. Others techniques may be used to implement interfaces in C++ (template, …), but there are out of scope of this article. 

In the first two parts of this series on resource owning, we’ve seen some good practices about resource owning: separating them from business code, how to offer a strong exception guarantee and how to have a cleaner code with the Copy and swap idiom. We’ve also seen that if one of destructor, copy constructor, copy assignment, move constructor, or move assignment operator is defined, all of them must also be defined, as stated by the Rule of five. In this part, we’ll see that this special member functions are only associated with resource owning classes, and shouldn’t be defined otherwise. But before that, we’ll optimize our assignment operators.

In the first part of this series on resource owning, we’ve seen that separating resource owning from business code is a good practice. We’ve also seen that if one of destructor, copy constructor or copy assignment operator is defined, all of them must also be defined, as stated by the Rule of three. In this part, we’ll get into the move semantic introduced by C++11 and cover the case of moving a resource owning object into another. But before that, we’ll fix the 3 issues of our first implementation.

I’ve seen too much code base mixing technical code with business one. Particulary, a lot of business code is owning technical resource. Trying to figure out what this code does is often a lot of pain. The resource owning code deserve its own class, independent of the business code. This is a good programming practice, well described in the Single Responsibility Principle. In this post, we will see what are the good rules of thumb to design a resource owning class, starting with the Rule of three.

Build with bootstrap, powered by Jekyll and hosted on GitHub Pages.

2018 - Now Jérôme DUMESNIL