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

标签 c++ for-loop c++11 segmentation-fault auto

<分区>

//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。因此,我得到了一个 vector ,其中一些指针指向有效内存,而其他指针只是新构造的指针,未设置为 null 或未提供任何地址。仍然有趣的是,第一个循环能够在不崩溃的情况下处理这个问题,而第二个循环出现了段错误。

关于c++ - C++11 段错误中基于范围的 for 循环,但不是常规 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12514617/

相关文章:

python - 迭代字典

c++ - 编译器生成构造函数来初始化成员

c++ - Qt5 lambda 连接内存泄漏的新信号

php - 如何在 C++ boost 中编写这些正则表达式?

c++ - 解析/etc/network/interfaces

c++ - 将任何类成员函数作为参数传递

c++ - 为什么我的递归函数按降序打印,然后按升序打印?

javascript - 带 for 语句的空表单

c++ - 'mutex' 不是 MinGW 5.3.0 中 'std' 的成员

java - 使用 Java For 循环产生这个结果