home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 32,596 of 33,346   
   =?ISO-8859-1?Q?Daniel_Kr=FCgler?= to All   
   Re: The dangers of returning const refer   
   19 Oct 12 15:31:41   
   
   From: daniel.kruegler@googlemail.com   
      
   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! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca