什么时候应该使用对象的向量而不是指针的向量? [英] When should I use a vector of objects instead of a vector of pointers?
问题描述
我有一个多态对象的集合,所有的派生自我的Animal类:Cat,Dog和MonkeyFish。
我通常的操作模式是存储这些对象在动物指针的向量中,像这样:
std :: vector<动物*> my_vector;
my_vector.push_back(new Animal_Cat
my_vector.push_back(new Animal_Dog());
my_vector.push_back(new Animal_MonkeyFish());
生活很棒...还是吗?
最近被告知,我应该真正尝试避免分配内存在这种方式,因为它使内存管理一个杂烩。当我需要销毁my_vector,我必须遍历所有的元素和删除一切。
我不认为我可以存储一个引用的向量(我可能错了这个),所以看起来像存储一个Animal对象的向量是我唯一的选择。
什么时候应该选择使用指针的矢量对对象的矢量?一般来说,哪种方法更好? (我想尽可能减少对象复制。)
你应该尽可能使用对象的向量; 但在您的情况下是不可能。
指针容器可以避免切片问题。但是,然后你必须调用删除每个元素,像你在做。这是烦人,但可能。不幸的是有一些情况(当抛出异常时),你不能确定删除是否被正确调用,并且你最终会出现内存泄漏。
解决方案是使用智能指针。 Pre-C ++ 11附带了 auto_ptr
,但不能在标准容器中使用。 C ++ 11具有设计为可在容器中使用的 std :: unique_ptr
和 std :: shared_ptr
喜欢 std :: unique_ptr
,除非我真的需要引用计数)。如果您无法使用C ++ 11,最佳解决方案是 Boost智能指针。 p>
I have a collection of polymorphic objects, all derived from my Animal class: Cat, Dog, and MonkeyFish.
My usual mode of operation is to store these objects in a vector of Animal pointers, like so:
std::vector< Animal * > my_vector;
my_vector.push_back( new Animal_Cat() ); my_vector.push_back( new Animal_Dog() ); my_vector.push_back( new Animal_MonkeyFish() );
And life is great...or is it?
I've recently been told that I should really try to avoid allocating memory in this fashion, because it makes memory management a chore. When I need to destroy my_vector, I have to iterate through all the elements and delete everything.
I don't think that I can store a vector of references (I might be wrong about this), so it seems like storing a vector of Animal objects is my only alternative.
When should I choose to use a vector of pointers versus a vector of objects? In general, which method is preferable? (I would like to reduce object copying as much as possible.)
You should use a vector of objects whenever possible; but in your case it isn't possible.
Containers of pointers let you avoid the slicing problem. But then you have to call delete on each element, like you are doing. That's annoying but possible. Unfortunately there are cases (when an exception is thrown) where you can't be sure that delete is properly called, and you end up with a memory leak.
The main solution is to use a smart pointer. Pre-C++11 comes with auto_ptr
, but that cannot be used in a standard container. C++11 has std::unique_ptr
and std::shared_ptr
which are designed to be usable in containers (I prefer std::unique_ptr
unless I really need reference counting). If you can't use C++11, the best solution is Boost smart pointers.
这篇关于什么时候应该使用对象的向量而不是指针的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!