For whatever reason, people staring out with STL and C++ tend to pass
vectors and hash tables and such around by value:
Example 4-1. A silly way to pass around a bunch of values
string ReadLine( istream & in );
vector<string> BreakUpString( string s );
vector<string> Process( vector<string> v );
main()
{
vector<string> words;
vector<string> results;
string s = ReadLine( cin );
words = BreakUpString( s );
results = Process( words );
...
} |
If you are doing this, assume you have made a mistake in your design
and try to think of an alternative. First, the call to
ReadLine
goes to a lot of trouble to make a string, which is then copied when
it's returned, then copied again to pass to the constructor of
s
(that line is a copy constructor), which copies all the data over, and
then all those temporary strings have to be destroyed. The call to
BreakUpString copies that string again, creates a vector of
strings, which is copied as it's returned, then all those strings are
copied into
words, and the temporary vector copy is destroyed.
Same thing happens all over again in the call to
Process. Don't
make your program do all that work for nothing. Pass by reference if
you must pass the whole thing, and pass iterators around rather than
whole containers.