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 31,826 of 33,346   
   Dave Harris to Roman W   
   Re: What will keep C++ going, given that   
   21 Jan 12 06:24:06   
   
   47a7cccd   
   From: brangdon@cix.co.uk   
      
   bloody_rabbit@gazeta.pl (Roman W) wrote (abridged):   
   > > if container is not local, compiler will have to call end()   
   > > function every iteration (simply because 'foo' can modify 'c'   
   > > and compiler has no way to prove it won't (unless it is   
   > > exceptionally smart with full program optimization).   
   > >   
   > > Obviously for_each does not have this problem.   
   >   
   > I don't see why it doesn't, unless it makes optimistic assumptions   
   > about what its third parameter (unary functor) does   
      
   It's because for_each is passed a copy of the end() iterator by value.   
   For_each isn't passed the container and doesn't know if the container   
   somehow changes.   
      
   For_each is less like:   
      for (auto i = c.begin(); i != c.end(); ++i)   
          body( *i );   
      
   and more like:   
      for (auto i = c.begin(), e = c.end(); i != e; ++i)   
          body( *i );   
      
   The latter being so easy to write, and only slightly more verbose, I   
   don't think for_each has a big advantage here. Although with lambdas:   
      
       std::for_each( c.begin(), c.end(), []( type &item ) {   
            body( item );   
       } );   
      
   the readability benefit over the second version is slightly more than   
   over the first because we eliminate e as well as i.   
      
   (If you do want a custom looping algorithm that knows about the container,   
   such is easier to write and use in C++11 than in C++03.)   
      
   -- Dave Harris, Nottingham, UK.   
      
      
   --   
         [ 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