Boost logo

Boost Users :

Subject: Re: [Boost-users] [unordered_map] Trying to understand some errors
From: Nat Goodspeed (nat_at_[hidden])
Date: 2011-05-03 16:59:31


On May 3, 2011, at 1:04 AM, Craig Longman <craigl_at_[hidden]> wrote:

> unordered_map< string, uint32_t > xrf1;
> unordered_map< string, uint32_t >::const_iterator& iter = xrf1.find( "hello" );
>
> This is something I've used many times with the other containers (well, std::map at least), but here I'm getting a conversion error. This is resolved by either removing the reference marker, or removing the const qualifier.
>
> Can someone explain this please? I'd always thought that applying const was easily done, and if so, then a reference should be sufficient, right? Unless the const cast is marked as explicit somehow?

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.

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 let's say you declared xrf1 as const unordered_map. That would probably compile - but the anonymous value returned by find() can be destroyed at the end of the statement, leaving you with a reference to a destroyed value and a ticket to Undefined Behavior.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net