Tre*_*key 7 c++ for-loop segmentation-fault auto c++11
//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.
Run Code Online (Sandbox Code Playgroud)
为什么第二个循环是segfaulting,而第一个循环不是?
编辑:
我是个骗子。
Tree_NodeT 指针正在创建,但未在Build_Tree_List 函数中的某处初始化为 nullptr。因此,我得到了一个向量,其中一些指针指向有效内存,而其他指针只是新构造的指针,未设置为 null 或给定任何地址。仍然有趣的是,第一个循环能够处理这个问题而不会崩溃,而第二个循环则出现了段错误。