Change
std::list<Bar> & getBars()
to
std::list<Bar> getBars()
This will in principle return by value, but there's copy construction eliding mechanism, so optimizing compilers should be able optimize
std::list<Bar> bars (getBars());
to not involve the copy constructor and just directly build bars
.
Additionally, in C++0x there is move constructor, so the above code is efficient even if copy/move is not elided away for any reason.
EDIT for the missed subclass question:
In general this is not possible to do cleanly in C++ (I'm assuming that Foo
is a superclass of Bar
, otherwise what you are doing makes little sense). It is probably possible with some reinterpret_cast
black magic, but I'd strongly advise against it.
Closest approximation is probably this (with getBars()
adjusted accordingly):
std::list <Bar*> bars (getBars ());
std::list <Foo*> foos (bars.begin (), bars.end ());
However, this imposes some non-trivial memory management burden on you. Using some sort of auto-pointers might help, but as far as I remember only shared_ptr
can be used in containers.
Finally, Foo
/Bar
class hierarchy should use virtual functions, otherwise what you want to do is almost certainly not going to work (i.e. unless you really want to ignore any overrides in the subclass).