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:
- Implicit casts from a smart pointer (to an instance) of a derived class to a smart pointer of a base class.
- Static casts from a smart pointer (to an instance) of a base class to a smart pointer of a derived class.
- 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:
ref_ptr<TransformNode> xformNode(new TransformNode()); ref_ptr<Node> node = xformNode; // Valid: implicit cast
Fragment #2: Static cast from a base class instance to a derived class instance. Note we called our static cast operator “ptr_cast”.
ref_ptr<Node> node(new TransformNode()); // Storing as a "more general" pointer ref_ptr<TransformNode> pxformNode = ptr_cast<TransformNode>(node); // Valid: explicit cast.
Fragment #3: Finally, the following code is invalid, and will trigger a compile-time error:
ref_ptr<SimpleSceneGraph> sg(new SimpleSceneGraph()); ref_ptr<Node> node = ptr_cast<Node>(sg); // Illegal conversion: types are not related
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.