我有一个类,到目前为止它一直持有另一个类的引用,因为它不拥有该类并且不负责管理它的内存。
class MyClass
{
OtherClass& m_other;
public:
MyClass( OtherClass& other ) : m_other( other ) {}
};
然而,在某些情况下,MyClass
是 m_other
的所有者,我希望删除MyClass
时也会删除 OtherClass
。但在某些情况下,它不是所有者。
在这种情况下,更合适的是使用两个类来表示这两种情况,还是使用一个封装了这两种情况(使用 unique_ptr)的单个类呢?例如:
class MyClassRef
{
OtherClass& m_other;
public
MyClassRef( OtherClass& other ) : m_other( other ) {}
};
class MyClassOwner
{
std::unique_ptr<OtherClass> m_other; // Never null
public:
MyClassOwner( std::unique_ptr<OtherClass> other ) : m_other( std::move( other ) ) {}
};
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
public:
MyClass( std::unique_ptr<OtherClass> managed ) : m_other( *managed ), m_managed( std::move( m_managed ) ) {}
MyClass( OtherClass& other ) : m_other( other ), m_managed() {}
};
这可能是一个比较简单的例子,但通常在处理分割情况时,是创建新类来处理这些情况更好呢,还是将尽可能多的情况封装在一个类中 - 到合理的程度。
编辑:第三个选项与第二个选项类似,即使用std::shared_ptr<T>
,例如:
class MyClass
{
std::shared_ptr<OtherClass> m_other;
public:
MyClass( std::shared_ptr<OtherClass> other) : m_other( other ) {}
MyClass( OtherClass& other ) : m_other( std::shared_ptr<OtherClass>( &other, []( OtherClass* p ){} ) ) {}
};
请注意,我希望
MyClass
仍然接受引用,以允许指向栈分配对象的指针;这就是为什么构造函数创建了一个具有自定义删除器的 shared_ptr<OtherClass>
,而不是删除栈对象。