Re: Variables in for loop (style issue)
Anders J. Munch wrote:
Thorsten Ottosen wrote:
> Anders J. Munch wrote:
>> It was your example. My rewrite has the same functionality. If
>> you think there are additional mutating operations that need to be
>> accounted for, then you should have included them in your
>> challenge.
>
> <g>
>
> Please consider them included in the challenge.
Details, please! Don't ask me to come up with a couple of mutating
operations that, without const, can't be implemented without giving up
on either encapsulation or performance. The problem is I don't
believe they exist - if you do, then you should provide the specifics.
It's fairly easy to see they do exist: just imagine a container
operations for which it is cheaper to modify one element than to
copy the whole object with one element replaced.
All I can do is show a random assortment of mutating operations that
most definitely _can_ be implemented. Bar is still immutable, of
course, but I'll have Foo grow a few methods that correspond to
changing the vector<int> in the original design:
class Foo
{
private:
Bar m_bar;
public:
Bar bar() const;
// Make bar() return bar_
void replace_all_of_bar(Bar bar_);
// Increase each element returned by bar() by one.
void inc_bar();
// Make bar()[index] return new_value.
void replace_bar_component(size_t index, int new_value);
};
Performance characteristics are different, when compared to the
original with a vector<int> member returned by const reference. Not
worse, not better, just different.
there's only three ways to characterize performance: either it is
slower, just as fast or faster. What you are saying is that
there's a fourth way: they have the same performance, but are different
anyway. What's the logic in that?
replace_bar_component has gone from O(1) to O(bar().size()) in the
straightforward implementation, which is bad.
That is pretty bad.
But, barring
copy-construction costs, replace_all_of_bar has gone from
O(bar().size()) to O(1), which is good.
It's still an O(bar().size()) operation.
For some types, copy-construction is faster or just as
fast as assigning a reference.
And overall performance
should be just fine, as long as I stick with high-level operations
such as inc_bar, instead of fiddling with individual low-level
elements using replace_bar_component.
What makes you think that is possible? A generic container cannot
assume very much about the elements it stores, and certainly not that an
element will be incrementable.
-Thorsten
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]