我只是想知道指针 vector 有什么问题。我的一些 friend 建议我使用列表而不是 vector 。这会导致问题吗:
vector<Fruit*> basket;
basket.push_back(new Apple());
basket.push_back(new Orange());
vector<Fruit*> temp;
temp.push_back(basket[1]);
如果我删除 vector temp,我是否也会破坏 basket[1] 对象?如果不是,使用指针 vector 有什么问题?
最佳答案
If I delete vector temp, do I destroy the basket[1] object too?
否。首先,你不能删除 temp
;相反,它会在超出范围时被销毁。当发生这种情况时, vector 元素指向的对象将不会被自动delete
d。
然而,这不是 vector
的特定问题:使用 list
不会使您免于此问题。问题在于原始指针。如果你希望指向的对象在最后一个指向它的指针的生命周期结束时自动释放,你应该使用智能指针。
根据您的应用程序需要的所有权策略,您可以在 shared_ptr
和 unique_ptr
之间进行选择。 shared_ptr
的注意事项是应避免引用循环,以防止相互引用的对象保持彼此存活。您可能需要在这方面检查 weak_ptr
。
最后,除非您有充分的理由不使用vector
,否则vector
应该是容器的默认选择。来自 C++11 标准的第 23.2.3/2 段:
The sequence containers offer the programmer different complexity trade-offs and should be used accordingly.
vector
orarray
is the type of sequence container that should be used by default.list
orforward_list
should be used when there are frequent insertions and deletions from the middle of the sequence.deque
is the data structure of choice when most insertions and deletions take place at the beginning or at the end of the sequence.
关于c++ - 指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15008521/