c++ - 指针 vector

标签 c++

我只是想知道指针 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 元素指向的对象将不会被自动deleted。

然而,这不是 vector 的特定问题:使用 list 不会使您免于此问题。问题在于原始指针。如果你希望指向的对象在最后一个指向它的指针的生命周期结束时自动释放,你应该使用智能指针。

根据您的应用程序需要的所有权策略,您可以在 shared_ptrunique_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 or array is the type of sequence container that should be used by default. list or forward_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/

相关文章:

c++ - HTTP 状态码到 HRESULT 的映射

c++ - CTAD、initializer_list、非显式构造函数和函数调用

c++ - 将链表从原始指针转换为智能指针

基于 C++ 文本的游戏(未知错误)

c++ - 以 CRuntimeClass 为键的 CMap

c++ - 无法从 Windows 注册表中查询值

c++ - 从 Lua 内部获取 Lua 状态,以便它可以传递回 C

c++ - 在 constexpr 表达式中检查具有公共(public)初始序列的 union 的非事件成员

c++ - 具有 CREATE_ALWAYS 处置的 CreateFile 函数

c++ - 运算符重载 : getting unidentifiable errors