Search code examples
c++templatesmemory-managementsmart-pointersreference-counting

Is it possible to create a simple smart pointer baseclass without templates?


I was wondering if it is possible to create a smart pointer baseclass without using a template?

I have seen a number of implementations but all use tempalates. For example, implementing the smart pointer logics in a base class which other classes derive from.


Solution

  • The problem is the class of your pointer member.

    In languages like C# it is possible, because there is an "object" class, from which every other class derives. You would lose type safety in that case.

    However, in C++ you don't have such a thing, which leaves you with 2 choices:

    1. Using void* and reinterpet_cast - very ugly, really not safe due to type safety.
    2. Writing tons of overloads for your class - for each and every class. Not feasible, because it will not work with new classes.

    Thus, the best way is to use templates.
    By the way, the idea of template is so good that C# started to use it after some version.