Yes, I agree -- the reason why you think it isn't very readable is because main() does everything.
But I want to point out one thing regarding Disch's statement
Define variables as you need them, but refrain from putting complex types inside loops: |
This isn't necessarily true. Consider the following functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void func1() {
for( int i = 0; i < 10; ++i )
{
std::vector< std::string > v( SomeFunc() );
DoSomethingWithIt( v );
}
}
void func2() {
std::vector< std::string > v;
for( int i = 0; i < 10; ++i )
{
v = SomeFunc();
DoSomethingWithIt( v );
}
}
|
In func1(), each time through the loop, std::vector<>'s copy constructor is run and later its destructor is run, meaning 20 total function calls. Contrast that to func2(), in which there is 1 obvious construction, 1 obvious destruction, and 10 assignments.
But what does std::vector<>'s operator= do? First, it has to destroy all elements contained by the vector and deallocate the memory used by the vector, [/i]which is essentially the same as what the destructor does[/i], and then it has to copy the right-hand side vector to the left,
which is essentially the same as what the copy constructor does.
The only difference, which in this case is nothing, is that a proper constructor would also have to set up vtables and a proper destructor would have to tear them down. However, vector<> neither inherits nor contains any virtual methods, so vector<> doesn't have a vtable.
Therefore, I can argue in the second example that the amount of work performed is equivalent to 22 function calls -- 11 copy constructors and 11 destructors -- which is actually
more than what func1() does.