[英]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*)
我的问题是使用
push_back()
将派生类添加到向量的末尾,并且在编译时说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.您应该完全避免使用
new
的产品。 Instead, you should use std::make_shared
to allocate your objects that will be managed by std::shared_ptr
s:相反,您应该使用
std::make_shared
来分配将由std::shared_ptr
管理的对象:
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. std::make_shared
向新分配的对象返回一个std::shared_ptr
而不是原始指针。 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.不仅使
std::vector::push_back
在这种情况下工作,而且在遇到异常时也不太可能泄漏内存。
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>
.因为你不想
push_back
一个Base*
而是一个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.使用
emplace
将允许在std::shared_ptr<Base>
的构造函数中使用Base*
,然后将其添加到您的向量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.