参照
自分がひと月前に書いたコードで先週発覚したバグ。
#include <list> struct THoge { int nValue1; double dValue2; }; void Delete( std::list< THoge >* const plsHoge ) { std::list< THoge >::iterator itr = plsHoge->begin(); while ( itr != plsHoge->end() ) { THoge& rstHoge = *itr; if ( ... ) { ++itr; continue; } itr = plsHoge->erase( itr ); // ここがまずい fprintf( stdout, "%d\n", rstHoge.nValue1 ); if ( rstHoge.dValue2 <= 0.0 ) { continue; } ... } }
自分でもびっくりしたorz
使っているライブラリがSTLportのv4.5系に依存していて、且つコンパイラがVC++7.1だったので、STLのイテレータの中身がデバッガから全く見えない状態になってしまうので、イテレータの操作をする時はポインタ又は参照で操作するようにしていたのが逆にバグの原因となってしまったな。
#include <list> struct THoge { int nValue1; double dValue2; }; void Delete( std::list< THoge >* const plsHoge ) { std::list< THoge >::iterator itr = plsHoge->begin(); while ( itr != plsHoge->end() ) { THoge* pstHoge = &(*itr); if ( ... ) { ++itr; continue; } int nValue1 = pstHoge->nValue1; double dValue2 = pstHoge->dValue2; pstHoge = NULL; itr = plsHoge->erase( itr ); fprintf( stdout, "%d\n", nValue1 ); if ( dValue2 <= 0.0 ) { continue; } ... } }