I just finish to implement a generic skip list in C++ an I want to bring it an
STL map-like iterator.
The problem arise when overloading the “->” operator: it is required to return a reference to an iterator::value_type, which in my case is std::pair, with K being the key type and V the value type of my map-like container.
The code is the following:
value_type& operator->() { return value_type(inner->key, inner->value); }
The compiler return me some hatred messages about references to temporary objects, and I
completely agree with him; me question is: How the hell should I do to return a reference
to a pair without having to put a pair member in my iterator class ?
Your return type is a reference to a
value_type, but you return a locally-created instance, which would be destroyed at the end of the function/operator scope (i.e. the closing}.) So you return a garbage reference, which is why your compiler hates you.If you instead return by value, you will have correct and functional code. (Whether or not you should return by value depends on the type of
value_type.)Even better would be to maintain a single
value_typeas a member field of your class, but you say you don’t want to, so this is the only other realistic option.