7
//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.

最初のループではセグメンテーション違反が発生しないのに、2 番目のループではセグメンテーション違反が発生するのはなぜですか?

4

2 に答える 2

3

forループの範囲は次と同等です。

for (auto it = xml_trees.begin(); it != xml_trees.end(); ++it) {
    auto tree = *it;
    if (tree){
        (tree)->Print(std::cout,4);
    }
}

違いは、forループの範囲が、逆参照されたイテレーターをコピー構築していることです。従来のforループと同様の動作を得るには、次を使用しますauto &

for (auto &tree: xml_trees){
    if (tree){
        tree->Print(std::cout,4);
    }
}
于 2012-09-20T14:40:20.357 に答える
3

編集:
私はうそつきです。
Tree_NodeT ポインターが作成されていましたが、Build_Tree_List 関数のどこかで nullptr に初期化されていませんでした。したがって、一部のポインターが有効なメモリを指しているベクトルが返され、他のポインターは null に設定されていない、またはアドレスが指定されていない、新しく構築されたポインターでした。最初のループがクラッシュすることなくこれを処理できたのに対し、2 番目のループは segfault が発生したことは興味深いことです。

于 2012-09-20T14:34:02.760 に答える