Re: STL Vector - pass by reference?



Gerry Hickman wrote:
Hi,

In an earlier thread entitled "STL vector - which style of for() loop?" I had a function that could populate a vector (with a variable number of strings) and pass it back to the caller, but people pointed out this would create a "copy" of the vector and it may be better to pass by reference. 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)
{
guids.clear();
// If you can estimate n, reserve can eliminate reallocations.
// guids.reserve(n);
...
returns guids.size();
}

----- example end -----

but when I came to actually code this, I ran into some problems. I managed to code something that appears to achieve the objective, but my code is almost "back-to-front" (in terms of * and &) of what Doug posted. Can someone clarify?

----- my attempt -----

using namespace std; // just for this demo

vector<string> guids;
PopulateStrings(&guids);
cout << "Count of guids is now " << guids.size(); // prints 2

void PopulateStrings(vector<string> * guids)
{
guids->clear();
guids->push_back("test1");
guids->push_back("test2");
}

----- end my attempt -----


There are two ways to "pass by reference." They are to pass a reference, or to pass a pointer. Doug showed using a reference, your version is using a pointer. Performance would be equal either way.

--
Scott McPhillips [MVP VC++]

.



Relevant Pages

  • Re: pass by Reference/value ???
    ... > void foo ... this would be called "passing by reference". ... foo receives a local copy of s and any changes that it makes to s only ... Since s is a pointer, a variable storing the address of s is a pointer to ...
    (comp.lang.cpp)
  • Re: basic question about references
    ... It expects a reference, ... not a pointer. ... void f; // a reference ... introduced for operator overloading because using ...
    (alt.comp.lang.learn.c-cpp)
  • Re: <OT> About pointer
    ... > void h{ ... > explicitly noting each place at which an underlying pointer mechanism ... passing "by reference" or passing a pointer ... > What does this program fragment print? ...
    (comp.lang.c)
  • Re: possibility to forbid use of "this"?
    ... >void DoSomething ... so a pointer can't implicitly convert to a shared_ptr. ... depending on what DoSomething does. ... DoSomething doesn't hold onto a reference to a, ...
    (comp.lang.cpp)
  • Re: Question on LSP
    ... Sure, the developer must keep track of which type has been assigned to each pointer to manage complexity in creating the design, which is why the 'T' is in T*. ... Subtyping is a relation which does not ... Those object types are completely orthogonal to the semantics of being an object reference. ... aggregate references, is the aggregate of referenced objects or target ...
    (comp.object)