Re: STL Vector - pass by reference?
On Fri, 10 Aug 2007 22:47:34 +0200, "Bo Persson" <bop@gmb.dk> wrote:
Doug Harrison [MVP] wrote:
:: On Fri, 10 Aug 2007 08:59:05 +0200, Ulrich Eckhardt
:: <eckhardt@satorlaser.com> wrote:
::
::: 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.
::
:: What's "funny" is to compare returning a vector<string> by value to
:: returning its size, the latter being as close to a free operation
:: as there is, both in terms of complexity and exception safety. Not
:: to mention, returning the size is a useful thing to do.
How do you know that it is useful? Always?
Often, after using a function with a name such as "GetDeviceClasses", a
programmer wants to know how many such classes were found; he may be
interested in the exact number, or he may just treat it as a boolean.
Provided one can indicate errors in some other way, there's no reason not
to return the number of items that were found, elements read, etc.
Assuming that we are trying to optimize a time-critical piece of code,
why return a value that isn't asked for? Especially as it is also
returned as a part of the guids parameter.
The code in question populates a vector<string>, and judging by its name,
probably enumerates the registry. I don't understand how anyone could worry
about the efficiency of returning vector::size() in this context.
(Granted, if you were talking about std::list, you might have a very, very
tiny point, but to date, I'm unaware of anyone making vector::size worse
than O(1).)
It is also often not considered good style to have both a return value
and out-parameters.
This is not an example of bad style.
(Q: What do you think this interface is equivalent to, if anything? To help
you focus, you can limit yourself to standard functions.)
If you need to, you can have several
out-parameters, and not single out one of them as a return value.
Yes, you can do that if you need to.
--
Doug Harrison
Visual C++ MVP