mercredi 31 juillet 2019

weak_ptr vs unique_ptr reference - passing interface impl to other object

Here is an example code:

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;
};

Class A contains an interface implementation and other object of type B. That object also need to use an interface implementation. I wonder which types of smart pointers should be used to create interface impl in class A and pass that impl to class B. Should I use shared_ptr in class A and weak_ptr in class B or unique_ptr in class A and a reference to unique ptr in class B ?

Aucun commentaire:

Enregistrer un commentaire