Boost logo

Boost :

From: Jonathan Wakely (cow_at_[hidden])
Date: 2005-04-27 05:03:42


On Tue, Apr 26, 2005 at 07:38:16PM +0100, Jason Earl wrote:

>
> On 26 Ebr 2005, at 19:23, Caleb Epstein wrote:
>
> >On 4/26/05, Philippe Mori <philippe_mori_at_[hidden]> wrote:
> >
> >>Since a Limousine is a Car, you should able to do
> >>
> >> Cars.insert(Cars.end(), Limousines.begin(), Limousines.end());
> >>
> >>at least if you have a recent compiler.

That might look nicer than the original, but only ...

> >And if you don't mind slicing your objects. You can't store
> >polymorphic types directly in std containers.

> Well that's easy enough to get round, use pointers. if you are storing
> objects in containers, it normally is good practice to use pointers
> anyway because the STL passes data round by value, and not my reference
> / pointer, and therefore unless your objects are very lightweight
> and/or have copy constructors, then storing objects by value is
> normally a big no-no in most cases.

I would argue that it is only good practice if your objects are
polymorphic, recommending storing raw pointers as generally "good practice"
is highly questionable, given the alternatives available today.

Who would own the pointee if you copy a Limousine* into vector<Car*> ?

Boost ptr_container is a better solution than raw pointers.

Or if you want to store by value but avoid excessive copying of heavyweight
objects don't use std::vector, use std::list or another container.

> ... One good exception to the rule here would be if you had smart
> pointers, obviously these objects are copied into the container, and
> these are lightweight and implement copy constructors / assignment
> operators. Generally, if you are going to use pointers, depending on
> the complexity of the object life-cycle, it is often wise to use
> something like boost::shared_ptr , as it will reduce the the risks of
> things like dangling pointers etc etc.

But conceptually storing a smart ptr is storing an object by pointer,
the fact that the smart ptr is stored by value is a distraction, you're
concerned with the pointee not the pointer.

*obviously* you store the actual smart ptr by value, storing a pointer
to a smart ptr in a container would be ludicrous!

jon

-- 
Rules of Optimization:
Rule 1: Don't do it.
Rule 2 (for experts only): Don't do it yet.
	- M.A. Jackson

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk