gpt4 book ai didi

c++11 - 所有权不一致

转载 作者:行者123 更新时间:2023-12-02 22:30:12 27 4
gpt4 key购买 nike

我有一个类,到目前为止,它引用了另一个类,因为它不拥有该类,也不负责管理它的内存。

class MyClass
{
OtherClass& m_other;
public:
MyClass( OtherClass& other ) : m_other( other ) {}
};

然而,在某些情况下,我面临的情况是MyClass是 m_other 的所有者,我想要删除以导致删除 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 ) ) {}
};

对比

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> 的原因使用自定义删除器不删除堆栈对象。

最佳答案

当类在某些情况下可能是所有者,而在其他情况下它不是所有者时,您应该使用 std::shared_ptr<T> ,它维护使用计数,代替 std::unique_ptr<T> ,这需要资源的唯一所有权。

只要m_other指向的对象的所有引用通过 std::shared_ptr<T> 维护智能指针,资源管理将为您自动化,无论程序的哪一部分拥有该对象。

关于c++11 - 所有权不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46517501/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com