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.some开发者_JS百科Int << 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->second
reference? 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")
.end()
on an STL container points to one past the end of the contained sequence. The iterator is only valid for comparison.
Under the hood it's a pointer, which you obviously can compare, but which might point to unmapped memory.
That is undefined behaviour, it could do nothing or it could give you a segment violation
精彩评论