dimanche 6 mai 2018

Copying shared_ptr

Here is my problem. I have an interface and two derived classes:

class Interface
{
public:
    virtual void f() = 0;
};
class Derived1 : public Interface;
class Derived2 : public Interface;

Then, I also have a Value class containing a shared_ptr whose purpose is point to one of the two derived classes:

class Value
{
public:
     Value();
     Value(const Value&);
private:
     shared_ptr<Interface> p_;
};

As I want my Value class to act like a value, I want my copy constructor to make a copy of the pointed Derived object. However, I can't write

Value::Value(const Value& value) : 
    p_(make_shared<Interface>(*value.p_))
{ }

as Interface contains a purely virtual function. *value.p_ must be a Derived type. I don't know how to manage this problem properly.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire