Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map::iterator references non-existing object?

Tags:

c++

stl

Considering the following code:

class MyClass
{
    public:
        int someInt;
        MyClass() : someInt(666) { }
};

int main()
{
    std::map<int,MyClass> myMap;
    std::map<int,MyClass>::iterator it = myMap.end();
    const MyClass& ref = it->second;
    std::cout << ref.someInt << std::endl;
}

Since the map is empty and it = myMap.end(), what Object does it->second reference? Is this an invalid reference because it = myMap.end()?

map<int,MyClass> does not create an instance of MyClass.

like image 745
DyingSoul Avatar asked Dec 19 '25 13:12

DyingSoul


2 Answers

what Object does it->second reference? Is this an invalid reference because it = myMap.end()?

Indeed. myMap.end() is a valid iterator but it must not be dereferenced. it->second attempts to do exactly that and causes undefined behaviour.

map<int,MyClass> does not create an instance of MyClass.

True, but irrelevant. myMap.end() will always – no matter the content of myMap – contain a reference to a “one past end” iterator which must never be dereferenced.

like image 111
Konrad Rudolph Avatar answered Dec 21 '25 03:12

Konrad Rudolph


std::map::end() returns the iterator to the first element after the last element in the map. If you try to dereference it, you will invoke an undefined behaviour (google for "C nasal demons")

like image 43
BЈовић Avatar answered Dec 21 '25 02:12

BЈовић