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

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,而第一个循环不是?

Tre*_*key 3

编辑:
我是个骗子。
Tree_NodeT 指针正在创建,但未Build_Tree_List 函数中的某处初始化为 nullptr。因此,我得到了一个向量,其中一些指针指向有效内存,而其他指针只是新构造的指针,未设置为 null 或给定任何地址。仍然有趣的是,第一个循环能够处理这个问题而不会崩溃,而第二个循环则出现了段错误。

  • 这就是未定义行为的本质,​​它是未定义的,所以任何事情都可能发生,甚至是[恶魔从你鼻子里飞出来](http://www.catb.org/jargon/html/N/nasal-demons.html)。 (7认同)