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.
what Object does
it->secondreference? Is this an invalid reference becauseit = 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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With