在 C++11 段错误中基于范围的 for 循环,但不是常规 for 循环
Range-based for loops in C++11 segfault, but not with regular for loop
//fills my vector with pointers.
//(some are pointing places, others are set to nullptr
vector<Tree_NodeT*> xml_trees {Build_Tree_List(program_options->Get_Files())};
//time to print them
for (auto tree = xml_trees.begin(); tree != xml_trees.end(); ++tree){
if (*tree){
(*tree)->Print(std::cout,4);
}
}
//this worked! No Segfaults!
//time to print them again
for (auto tree : xml_trees){
if (tree){
tree->Print(std::cout,4);
}
}
//Crash! Segfault.
为什么第二个循环是段错误,而第一个循环不是?
编辑:
我是个骗子。
正在创建Tree_NodeT指针,但未在Build_Tree_List函数中的某个位置初始化为 nullptr。 因此,我得到了一个向量,其中一些指针指向有效内存,而其他指针只是新构建的指针,未设置为 null 或给定任何地址。 仍然有趣的是,第一个循环能够在不崩溃的情况下处理这个问题,而第二个循环则出现段错误。
循环的范围相当于:
for (auto it = xml_trees.begin(); it != xml_trees.end(); ++it) {
auto tree = *it;
if (tree){
(tree)->Print(std::cout,4);
}
}
不同之处在于,循环的范围是复制构造取消引用的迭代器。 要获得与传统 for 循环类似的行为,请使用 auto &
:
for (auto &tree: xml_trees){
if (tree){
tree->Print(std::cout,4);
}
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- C++ Python 循环"for i, num in enumerate(list):"版本
- C 多循环 for () 基础知识
- 没有条件值的 FOR 循环"for (int i = 1; ; i++)"无法正常工作
- 为用户提供循环for循环的选项
- 打破循环for循环