在 C++11 段错误中基于范围的 for 循环,但不是常规 for 循环

Range-based for loops in C++11 segfault, but not with regular for loop

本文关键字:循环 for 常规 范围 于范围 段错误 C++11 错误      更新时间:2023-10-16
//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);
    }
}