"Andrew Ward" <an*******@ihug.co.nz> wrote in message
news:2t*******************@news.xtra.co.nz...
Hi,
A third-party container library I use implements its containers using
copy-on-write semantics, making it efficient to return an instance of the
container by value from a function. For example:
ThirdPartyContainer<MyClass> foo();
If I want to refactor this function to use std::list I could do this:
std::list<MyClass> foo();
Which as far as I know could be either efficient or inefficient depending
on the library implementation.
What I wanted to know is what technique other people use? I can think of a
few other ways of writing the function:
void foo(std::list<MyClass> * toFill);
or
void foo(std::list<MyClass> & toFill);
or
std::auto_ptr<std::list<MyClass> > foo();
None of which are as easy to use as the return by value approach.
I prefer the approach of passing a reference. This is the way I often
handle such problems, regardless of what kind of container or object it is
I'm talking about. Even plain C-style arrays are often best handled like
this (assuming you're stuck using them in the first place), where you pass
the function a pointer to the first element (and a count of the elements),
and let them go to town on it.
I think of it like this: I'm giving someone a blank form which they need to
fill out. This leaves me in complete charge of the lifetime of the "form",
from its construction through its destruction, and all I ask of others
(i.e., functions), is that they use the form I give them, whether that's
filling it out, editing it, or building some kind of report from it.
This approach means I never get confused about who "owns" a dynamically
allocated object, and cleanup is much easier to handle.
-Howard