On 03/05/2011 4:59 PM, Nat Goodspeed wrote:

>     unordered_map< string, uint32_t > xrf1;
>     unordered_map< string, uint32_t >::const_iterator& iter = xrf1.find( "hello" );
> 

This code makes me shudder. Capturing the value returned from a function with a reference variable asserts
that the function is itself returning a reference, not a value - and always will, for the life of the codebase.

This is far more general than iterators.

My rule of thumb is: return by value, store returned data by value.
Perhaps a bit dramatic, but you're quite right.  =)
And it is something I'm (normally) aware and careful of.  Returning values is getting more and more acceptable as the optimizations get better and better.  However, references do have their place, even in return values.

I'm actually honestly not sure where I picked that up with iterators, but it worked and I guess it just kinda stuck.  I try and use references over copies where appropriate, and as it seemed to work.  I didn't think it through properly.
To answer your question, because xrf1 isn't const, its find() returns a non-const iterator. You're trying
to capture a reference to a const_iterator, which isn't what you have in hand.
But, the confusion is if I replace unordered_map with std::map, it compiles fine.  I guess that means in std::map a const_iterator is just that, a "const iterator", but in unordered_map, the const_iterator is a completely different type, not just a const version of the normal iterator?  I was under the impression that const could and would always be implicitly applied if needed, just not the other way round (obviously).

Time to dig through some header files I guess.

Thanks,

--

Craig Longman

If it's not signed by me, then please don't assume it is from me.