Improving Vortex’s Smart Pointers

In out last post, we talked about the shift we are currently making in Vortex, moving towards reference-counted resource management.

In this context, one of the problems we mentioned was the fact that due to the fact that C++ does not provide out-of-the-box type covariance/contravariance like C#, we ended up with some rather uncomfortable constructs for dealing with polymorphic data types.

Now, one of the great features of C++ is that the language is super-extensible. You can literally change the way many things work in C++ and, it turns out that after some research and experimentation (and a little C++ magic too), we found a way to implement C# covariance/contravariance for our custom smart pointers!

The latest improvements enable the following features:

  1. Implicit casts from a smart pointer (to an instance) of a derived class to a smart pointer of a base class.
  2. Static casts from a smart pointer (to an instance) of a base class to a smart pointer of a derived class.
  3. Compile-time errors from attempting invalid casts.

The following code fragments illustrate these points. These are taken directly from out test suite, with minor adaptations to simplify readability.

Fragment #1: Implicit cast from derived instances to base class instances:

Fragment #2: Static cast from a base class instance to a derived class instance. Note we called our static cast operator “ptr_cast”.

Fragment #3: Finally, the following code is invalid, and will trigger a compile-time error:

We are very happy with the result and are looking forward to continue migrating the Vortex codebase to our new smart pointers. Programming with Vortex just got a whole lot easier and safer.