简体   繁体   中英

Vector of shared_ptr of a abstract bass class pointing to derived classes

I am in a class where I am supposed to create a vector of shared pointers with an abstract base class and a two level hierarchy for derived classes.

class Base
{
   virtual string returnName() = 0;
};

class DerivedOne : public Base
{
private:
   string name;

public:
   DerivedOne()
   {name = "Derived";}

   virtual string returnName()
   {return name;}
};

class DerivedTwo : public DerivedOne
{
private:
   string secondName;

public:
   DerivedTwo()
   {secondName  = "DerivedTwo";}

   virtual string returnName()
   {return secondName;}
};

int main()
{
   vector<shared_ptr<Base>> entities;
   entities.push_back(new DerivedOne());

   return 0;
}

My issue is with adding a derived class to the end of the vector using the push_back() and when compiling it says no matching function for call to 'std::vector<std::shared_ptr<Base> >::push_back(DerivedOne*)

How would I add an initialized derived class to the vector?

You should avoid using a raw new at all. Instead, you should use std::make_shared to allocate your objects that will be managed by std::shared_ptr s:

entities.push_back(std::make_shared<DerivedOne>());

std::make_shared returns a std::shared_ptr to the newly allocated object rather than a raw pointer. Not only that make std::vector::push_back work in this case, it's also less likely to leak memory in the face of exceptions.

You'd need to replace this line with

entities.emplace_back(new DerivedOne());

because you don't want to push_back a Base* but rather a std::shared_ptr<Base> . Using emplace will allow the Base* to be used in the constructor of std::shared_ptr<Base> which is then added to your vector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM