Re: STL Vector - pass by reference?
Gerry Hickman wrote:
Doug Harrison offered this example:
----- example start -----
I would use pass-by-reference to avoid this needless cost, e.g.
vector<string>::size_type
void GetDeviceClasses(vector<string>& guids)
{
[...]
returns guids.size();
}
Funny. Talking about needless costs and then returning redundant data - the
size can be retrieved from the vector. Anyway, why would you write anything
but clear code unless you first determined that it's a bottleneck? Just
return the vector by value.
but when I came to actually code this, I ran into some problems.
This doesn't help. What problems?
void PopulateStrings(vector<string> * guids)
{
guids->clear();
guids->push_back("test1");
guids->push_back("test2");
}
While this code will work, there is one thing I object to: in C++, where you
have references, a pointer[1] means to me that something is optional, i.e.
passing zero is okay, but you don't mean that. Still, you must handle that
case, so either you just return (making it a non-error), throw an exception
(making it a runtime error) or use assert() (making it a programmer's
error).
Not checking it is bad practice and will get you larted if you happen to be
on my team.
Uli
[1] The exception is when an array/string is passed.