I have a problem with assigning an unintialized to an initialized iterator. The following code excerpt produces an access violation when built with Visual Studio 2010. In previous versions of Visual Studio the code should work.
#include <list>
int main() {
std::list<int> list;
std::list<int>::iterator it = list.begin();
std::list<int>::iterator jt;
it = jt; // crashes in VS 2010
}
Wouldn’t this be considered valid C++?
I need this code to implement a “cursor” class that either points nowhere or to a specific element in a list. What else could I use as a value for an uninitialized iterator if I don’t have a reference to my container yet?
This invokes undefined behaviour (UB). According to the C++ Standard ,
jtis a singular iterator which is not associated with any container, and results of most expressions are undefined for singular iterator.The section §24.1/5 from the C++ Standard (2003) reads (see the bold text specifically),
If MSVS2010 crashes this, it is one of infinite possibilities of UB, for UB means anything could happen; the Standard doesn’t prescribe any behavior.