指向向量和多态性的唯一指针
我有问题,我想创建指向 Base 对象向量的唯一指针.我想保留 Base 的这个向量子类(SubClass
),但是初始化有问题,因为 Base 类是虚拟的.
I have problem, I want to create unique pointer to vector of Base objects.
I want keep in this vector subclass of Base (SubClass
), but i have problem with initialization, because Base class is virtual.
std::unique_ptr<std::vector<Base>> baseVector = std::make_unique<std::vector<Base>>();
SubClass newObject();
baseVector->push_back(newObject);
推荐答案
短版:你不想要一个指向 Base
集合的动态指针;你想要一个指向Base
的动态指针集合.
Short Version: You don't want a dynamic pointer to a collection of Base
; you want a collection of dynamic pointer-to-Base
.
您似乎误解了在多态集合中放置 std::unique_ptr
的位置.不是集合需要成为多态工作的指针;它是里面的对象.
You seem to be misunderstanding where to place std::unique_ptr
in your polymorphic collection. It isn't the collection that needs to be pointers for polymorphism to work; it's the object held within.
例如:
#include <iostream>
#include <vector>
#include <memory>
struct Base
{
virtual ~Base() {}
virtual void foo() const = 0;
};
class DerivedOne : public Base
{
public:
virtual void foo() const
{
std::cout << "DerivedOne
";
}
};
class DerivedTwo : public Base
{
public:
virtual void foo() const
{
std::cout << "DerivedTwo
";
}
};
int main()
{
std::vector< std::unique_ptr<Base> > objs;
objs.emplace_back(std::make_unique<DerivedOne>());
objs.emplace_back(std::make_unique<DerivedTwo>());
// via operator[]
objs[0]->foo();
objs[1]->foo();
// via range-for
for (auto const& p : objs)
p->foo();
// via iterators
for (auto it = objs.begin(); it !=objs.end(); ++it)
(*it)->foo();
}
输出
DerivedOne
DerivedTwo
DerivedOne
DerivedTwo
DerivedOne
DerivedTwo
您是否希望通过智能指针动态管理集合本身与此问题无关(并且有些疑问).
Whether you want the collection itself to be managed dynamically via a smart pointer is unrelated (and somewhat questionable) to this issue.
相关文章