Re: does map find guarantee to not copy mapped value?
PeteUK wrote:
Hello,
I find myself writing a lot of code like the one below where I find
something out of a map and then use a reference to second to
interrogate the mapped object:
#include <iostream>
#include <map>
class Expensive { /* lots of stuff here... */ };
int main()
{
std::map<int,Expensive> m;
m.insert(std::make_pair(1,Expensive(3)));
// and then later
std::map<int,Expensive>::const_iterator it = m.find(1);
const Expensive& expensive = (*it).second;
// use expensive here - is this safe?
}
Is this practice safe?
Operations on map don't invalidate references unless they erase the element
referred to. The same guarantee applies to iterators and pointers into the
map.
I've just determined on VC9 compiler that the
find doesn't do any copies, but wondered if the standard mandates
this?
Yes: [23.1/11] and [23.1.2/8] and the absence of invalidate-clauses in the
section about std::map.
Best
Kai-Uwe Bux