C++迭代器需要删除吗?

标签 c++ memory

我有一个关于内存释放的问题

我正在我的一个程序中迭代一个 vector 。像这样:

// init vector
vector<int>* v = new vector<int>();
// iterate
for (vector<Column>::iterator it = v->begin(); it != v->end(); ++it) {
    // do something with it
}
// delete vector
delete v;

但是我不确定是否应该这样写:

// init vector
vector<int>* v = new vector<int>();
// iterate
vector<Column>::iterator it = v->begin()
for (; it != v->end(); ++it) {
    // do something with it
}
delete it;
// delete vector
delete v;

或者因为释放了迭代器而没有必要释放迭代器?

最佳答案

您只能对迭代器持有的对象调用 delete,而不是迭代器本身;以您的代码为例(但稍作修改):

std::vector<int*> *v = new std::vector<int*>();
for (int i = 0; i < 10; ++i) {
    v->push_back(new int(i));
}
std::vector<int*>::iterator it = v->begin();
for (; it != v->end(); ++it) {
    // do something with it
    delete *it; // <- notice the deference to delete the underlying int 
    //delete it; // causes compiler error (expected pointer)
}
// delete vector
delete v;

在迭代器类型上调用 delete 会产生编译器错误(取决于编译器/实现等)。

关于C++迭代器需要删除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23578455/

相关文章:

c++ - 本地 WideString 变量调试错误 "Int3 DbgBreakPoint"

c++ - 在使用 NaCl 的 C++ 中,如何按值对 JSON 对象进行排序?

c# - 如何使程序集的后续实例共享相同的内存?

c++ - 当前内存使用显示总是比任务管理器多 ~14MB

c++ - 使用 std::map 的内存爆炸

c++ - 如何使用 stringstream 在字符串中保留引号?

c++ - 错误 : invalid conversion from 'unsigned char*' to 'const signed char*'

java - JNA 使用 32 位 JVM 运行时内存访问无效

c++ - 为什么 boost::thread 构造函数不接受 boost::thread::attributes 参数?

memory - 无硬件支持的虚拟内存