<
age...@andrewpetermarlow.co.uk> wrote:
> 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 return references all the time in such situations. References are
seldomly stored for longer than a few function calls, but mostly
directly forwarded to other functions as arguments, which are often
also references. If I still want to store it for longer, I'll store a
copy and not a reference, unless I'm totally sure that the reference
will not invalidate. By returning a reference, you let the caller
decide, whether to copy the object or not.
> 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).
Knuth may be a smart guy, but I just cannot hear that that quote
anymore. People look at others code and think they know the problems
better than the one that actually wrote it. How can you say that an
optimization is premature if you weren't there when the code was
written?
I usually try to write performant code from the beginning. All those
small optimizations sum up and will make a difference in the end.
Optimizing the performance afterwards may not be that easy, because
the performance loss is not obviously concentrated in one spot.
It's even more true, if you write a library, or at least a reusable
class. You will never know in advance where and how your classes will
be used. And later, you may not have time/resources to look at the
code again.
> The code was drawn to my attention because purify gave it an UMR
> (uninitialised memory reference).
I don't know purify, but for me UMR seems to be a different problem
than the one you are describing (which is usually called dangling
reference).
This is my understanding of an UMR:
int obj; // not initialized
int& ref = obj; // UMR
> 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'm not an STL expert at all, but could it be, that the problem lies
actually somewhere else?
Tobi