在堆上创建多态对象的数据成员向量? [英] Create a data member vector of polymorphic objects on the heap?
问题描述
我有一个继承层次结构,其中A是一个抽象的基类,B和C是多态的孩子。
我想有一个向量类数据成员,在堆,它可以包含B和C对象。
所以在头文件中我有我的
向量< A *>多态性
并且在构造函数中我试图做:
polymorphicobjs = new vector< A>();
但显然这不会工作。如何实现这一点?
你不必担心保存 std :: vector
的原指针。它将为您创建很多麻烦,以后确保您在正确的时间删除对象。您应该做的是存储一个托管多态对象的容器(使用智能指针)。声明您的向量:
std :: vector< std :: unique_ptr< A>多态性
现在你可以很容易地在向量中存储多态对象(其中 B
是 A
的子类别:
polymorphicobjs.push_back(std :: unique_ptr< B>(new B));
这样,你不必担心调用 delete
上的对象。一旦你放手的向量(例如,当它超出范围在你的函数,或者它是自动破坏,如果它是一个类成员),对象将被删除。
但我需要与其他代码共享对象吗? p>
如果是这种情况,则 std :: unique_ptr
不是正确的选择。我们可以使用 std :: shared_ptr
表示对象已共享:
std :: vector< std :: shared_ptr< A>>多态性
// [...]
polymorphicobjs.push_back(std :: make_shared< B>());
push_back
不同于独特和共享?
因为C ++ 14还没有出来。如果你足够幸运使用一个新的足够的编译器(出血边缘clang / gcc / VS2013),独特的版本将看起来非常相似:
// C ++ 14
std :: vector< std :: unique_ptr< A>多态性
// [...]
polymorphicobjs.push_back(std :: make_unique< B>());
I have an inheritance hierarchy where A is an abstract base class and B and C are polymorphic children.
I wish to have a vector class data member, on the heap, which can contain B and C objects.
So in the header file I have my
vector<A*> polymorphicobjs;
and in the constructor I tried to do:
polymorphicobjs = new vector<A>();
but obviously this wouldn't work. How do I achieve this?
解决方案You shouldn't worry about keeping a
std::vector
of raw pointers. It will create a lot of hassles for you later on making sure you delete objects at the right time. What you should do is store a container of "managed" polymorphic objects (using smart pointers). Declare your vector:std::vector<std::unique_ptr<A>> polymorphicobjs;
And now you can store polymorphic objects in the vector pretty easily (where
B
is a subclass ofA
):polymorphicobjs.push_back(std::unique_ptr<B>(new B));
With this, you don't need to ever worry about calling
delete
on the objects in your vector. As soon as you "let go" of the vector (eg, when it goes out of scope in your function or it's automatically destructed if it's a class member), the objects will be deleted. The vector uniquely owns the objects.But I need to share the objects with other code?!
If that's the case, then
std::unique_ptr
isn't the right choice. We can express that the objects are shared by usingstd::shared_ptr
:std::vector<std::shared_ptr<A>> polymorphicobjs; // [...] polymorphicobjs.push_back(std::make_shared<B>());
Why does the
push_back
look different for unique and shared?Because C++14 isn't out yet. If you're lucky enough to use a new enough compiler (bleeding edge clang/gcc/VS2013), the unique version will look very similar:
// C++14 std::vector<std::unique_ptr<A>> polymorphicobjs; // [...] polymorphicobjs.push_back(std::make_unique<B>());
这篇关于在堆上创建多态对象的数据成员向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!