On Dec 3, 8:08*am, ittium <itt...@gmail.com> wrote:
> Group,
> I have a class that contains (STL) map of maps. This Class has a getMap
> function that return one map out of the map of maps. I need to avoid
> copies while extracting the map.
Your question is full of irrelevant details. Your class in "I have a
class" doesn't matter. STL doesn't matter. Map of maps doesn't matter.
There's one thing that's actually relevant, and that is: how to return
an object from a function, if the price to copy the object is
prohibitive.
When you ask like that, the answer is easy: you can't. The only way to
avoid a copy is to return a reference. That's it.
If your function needs to find something, and you deem absence of that
something a normal occurrence, you might want to return a pointer.
> There are two approaches
> 1. I pass a "map" reference in getMap function, the getMap method
> extract appropriate map and put it in the passed map reference. It seems
> copy will be made while doing
> * * * * map=Extracted Map; //map is reference parameter in getMap function
>
> 2. Second option is to return a reference from the getMap function
> (please ignore dangling pointer issue since this class is likely to live
> forever). My doubt is
> * * * * - Can I return a iterator->second as reference
Yes, provided that you don't erase the actual map entry later.
> * * * * - If I can return it, how can caller save it (without making a copy).
Only by keeping the reference. That's it. If you need to copy that
around, you'll need a pointer (p = &thing_returned_from_function).
Goran.
|