Prev: Is there any standard/guarantees for exception safety in STL operations?
Next: Is there any standard/guarantees for exception safety in STL operations?
From: red floyd on 28 Jul 2010 22:15 On 7/25/2010 8:18 AM, Dragan Milenkovic wrote: > On 07/21/2010 03:04 PM, red floyd wrote: > [snip] >> >> In addition to why Daniel said... think about this: >> >> If you passed by const-ref, and the functor had changeable state, >> said member variables would need to be declared mutable. > > But does that state even have a meaning if the change is done > on a local copy? My bet is that if I indeed needed a state, > I would require it to live longer than one function call. > Contrived example: you want to sum every other member of a container. You want to use accumulate: struct sum_odd_members : public std::binary_function<int, int, int> { bool sum_this_element; int operator()(int x, int y) { if (sum_this_element) x += y; sum_this_element = !sum_this_element; return x; } sum_odd_members() : sum_this_element(true) { } }; Container<int> c; int sum_of_every_other_member = std::accumulate(c.begin(), c.end(), 0, sum_odd_members()); If functors were passed by const ref, this sort of (contrived) example would be impossible, unless sum_this_element was mutable. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |