Home > OS >  unique_ptr to a derived class as an argument to a function that takes a unique_ptr to a base class a
unique_ptr to a derived class as an argument to a function that takes a unique_ptr to a base class a

Time:02-05

I have already read various comments similar to this question here on stack overflow without finding exactly the solution to my problem. I have a Base class and Derived class an also a class that contain and also keep the ownership of this objects.

class Base { };
class Derived: public Base { };

class MyClass
{
  std::vector<std::unique_ptr<Base>> myVector;
public:
  MyClass() {}

  void addElement (std::unique_ptr<Base> &base)
  {
    myVector.push_back(std::move(base));
  }
};

My code fails to compile when I try to add a derived object in my class.

MyClass myClass;

auto b = std::make_unique<Base>();
myClass.addElement(b);

auto d = std::make_unique<Derived>();
myClass.addElement (d); // <-- ERROR: error: cannot convert ‘std::unique_ptr >’ to ‘std::unique_ptr&’

CodePudding user response:

The function must accept the unique_ptr by value:

  void addElement (std::unique_ptr<Base> base)
  {
    myVector.push_back(std::move(base));
  }

and then call the member function like this:

MyClass myClass;

auto b = std::make_unique<Base>();
myClass.addElement(std::move(b));

auto d = std::make_unique<Derived>();
myClass.addElement(std::move(d));

or even better avoid the variables because you cannot use them anyway after the function call:

MyClass myClass;

myClass.addElement(std::make_unique<Base>());

myClass.addElement(std::make_unique<Derived>());
  •  Tags:  
  • Related