Search code examples
c++inheritancelanguage-designshared-ptr

Building an Object System Around shared_ptr


I am using shared_ptr as my garbage collection for a toy language that I am working on which compiles to C++. My objects derive from a common base class above that there are strings and numbers then there are vectors and maps. Everything on the c++ side is passed wrapped in shared_ptrs so my containers actually hold shared_ptr so that when they get destroyed their content is destroyed too. This scheme works but it feels a bit weird in that containers that are base objects are holding shared_ptrs. Is there a flaw with my design? If yes what would be an alternative hierarchy around this approach?


Solution

  • Here's how I'd set this up:

    namespace toylang {
    
    class Object;
    // main handle type; use this for all object references
    // replace with boost::intrusive_ptr or similar if too inefficient
    typedef std::shared_ptr<Object> obj;
    
    class Object
    {
        // whatever
    };
    
    class Number : public Object
    {
        int x;
        // etc
    };
    
    class Array : public Object
    {
        std::vector<obj> a;
        // etc
    }
    

    Note that ToyLang arrays in this scheme are vectors of pointers, giving the language reference semantics. This is in fact quite common in dynamic languages: Lisp, Python, and others work like that. As long as you don't have circular references, shared_ptr's reference counting will give you proper garbage collection.