neak_ptr vs unique_ptr参考 - 传递接口inmand tos to其他对象

weak_ptr vs unique_ptr reference - passing interface impl to other object

本文关键字:ptr tos inmand to 对象 接口 其他 unique vs 参考 neak      更新时间:2023-10-16

这是一个示例代码:

class Interface
{
public:
    virtual ~Interface(){}
    virtual void fun() = 0;
};
class InterfaceImpl: public Interface
{
public:
    void fun() override
    {}
};
class B
{
public:
    B(const std::shared_ptr<Interface>& impl /*std::unique_ptr<Interface>& impl* ?*/): impl_(impl){}
private:
    std::weak_ptr<Interface> impl_;
    //std::unique_ptr<Interface>& impl_; ?
};
class A
{
public:
    A(): impl_(std::make_shared<InterfaceImpl>()), b(impl_){}
private:
    std::shared_ptr<Interface> impl_;
    //std::unique_ptr<Interface> impl_ ?
    B b;
};

A类包含接口实现和类型B的其他对象。该对象还需要使用接口实现。我想知道应使用哪种类型的智能指针在A类中创建界面Inment ins Inmand Inment in Impt to类别。B?

我相信默认选择应该是拥有 InterfaceA应该由 unique_ptr持有。然后,不拥有InterfaceB应通过正常参考或原始指针保持。

unique_ptr的引用很少有意义。它没有提供原始指针或正常参考的其他安全保证,但会增加所有权的困惑。

class Interface
{
public:
    virtual ~Interface(){}
    virtual void fun() = 0;
};
class InterfaceImpl: public Interface 
{
public:
    void fun() override
    {}
};
class B
{
public:
    B(const Interface& impl): impl_(impl){}
private:
    const Interface& impl_;
};
class A
{
public:
    A(): impl_(std::make_unique<InterfaceImpl>()), b(*impl_){}
private:
    std::unique_ptr<Interface> impl_;
    B b;
};

这是假设B的寿命比A的寿命短,因此B可以保证Interface还活着。如果您不能保证该保证,那么您可以开始考虑shared_ptrweak_ptr对,但我认为这应该是您的首选。在您的情况下,您可以保证。

至于B是否应保存正常参考或原始指针,该指针归结为impl_是否可以为null(在这里似乎并非如此(。另外,持有参考可以限制您对B的操作。它使其不可分配,您无法重设引用指向不同的inmand。