Re: The dangers of returning const references to values held in a map
Am 19.10.2012 22:43, schrieb agents@andrewpetermarlow.co.uk:
I have come across some code that returns a const reference to a value
held in a map. Both the keys and the values are strings. I think that
the author might have been concerned about performance costs if the
returned value was to be copied. But I think this is wrong (premature
optimisation is the root of all evil). The code was drawn to my
attention because purify gave it an UMR (uninitialised memory
reference). This is what made me look at it, scratching my head to
find out how a UMR could happen. I have an educated guess and would
like to share it here to see what you STL experts have to say :-)
I think we need to see more concrete code that shows the operations
applied and the scopes of the corresponding objects to give more than
educated guesses here.
My guess is that because a std::map can be implemented using a tree
that can dynamically rebalance (typically a RB tree) it is dangerous
to return a reference to a value object held in that map. If the tree
were rebalanced then the reference might become invalid. Any thoughts?
The standard imposes quite strong implementation constraints upon
associative containers in regard to the conservation of iterator values
and references to contained elements. E.g. 23.2.5 p9 says:
"The insert and emplace members shall not affect the validity of
iterators and references to the container, and the erase members shall
invalidate only iterators and references to the erased elements."
In other words: Any rebalancing of the internal tree is not allowed to
invalidate references of existing elements. This is quite easy to
realize, because such containers are typically node-based, so
rebalancing will only move the nodes around without affecting the actual
(and observable) elements.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]