dimanche 1 octobre 2017

Inconsistent Ownership

I have a class that up until this point had a reference to another class because it didn't own that class and was not responsible for managing it's memory.

class MyClass
{
    OtherClass& m_other;
};

I am however in a situation where in some cases MyClass is the owner of m_other and I'd like a deletion to lead to the deletion OtherClass. And in some cases it isn't the owner.

In this instance, is it more appropriate to have two classes to represent both cases or to have a single class that encapsulates both cases (with a unique_ptr). e.g.

class MyClassRef
{
    OtherClass& m_other;
};

class MyClassOwner
{
    std::unique_ptr<OtherClass> m_other; // Never null
};

vs

class MyClass
{
    OtherClass& m_other; // class may or may not be the one we manage.
    std::unique_ptr<OtherClass> m_managed; // May be null
};

This is probably a rather simple example, but in general when dealing with split cases is it better to create new classes to handle these cases... or to encapsulate as many cases in a single class - to a reasonable level.

Aucun commentaire:

Enregistrer un commentaire