Interesting bug - Reminds handling of temp objects in c++

     Recently, i happened to come across this section of code causing a fault

  sampleClass object;
std::vector::iterator it;

for(it=object.someFunction().begin();it < object.someFunction().end();it++)
{
         // code to de-reference the iterator (it->)
}

      At first look, it looked fine and there didn't seem to be any problem. someFunction() returns a vector of type otherClass and the de-reference was causing a fault. Upon closer look, we found that someFunction() was returning the vector by value (a very bad design) and new temporary objects were created in the for loop control expressions. This temporary objects lifetime ends at the end of the control expression (as soon as .begin() or .end() is executed) and iterator (it) became a dangling reference and subsequent access in the body of the loop caused the fault. Enjoyed figuring this one out :-)

No comments: