(Mar 14, 2008)
Alias can be a tricky problem in C++'s STL vector.
Sometimes, I don't want to write an awkward code such as willFail.m_vecProblematic[0] all the time, so I create an alias (prob1 in this example). This alias will work fine until we push or pop elements in a vector to a certain number and the vector is needed to reallocate.
Problematic* prob1 = &( willFail.m_vecProblematic[0] );
prob1->m_vec2.push_back( 55 );
prob1->m_vec1.push_back( 11111 );
// Push an element to a vector may cause a vector to reallocate.
willFail.m_vecProblematic.push_back( Problematic );
// prob1 may not point to a correct storage, but this value assignment
// may not cause a program to crash instantly.
prob1->i = 24;
// prob1 may not point to a correct storage, and such object
// operation usually cause a program to crash
prob1->m_vec2.push_back( 66 );
Note: simple value assignment to an invalid place may not cause a program to crash so easily, but calling a method from an invalid object pointer will cause a program to crash very easily since the method table of an object is already messed up. If we want to find where a program goes wrong, we may try to call a method of a suspecious object pointer.
No comments:
Post a Comment