
--- At Wed, 4 Feb 2004 15:29:50 +0200, Peter Dimov wrote:
Joshua Little wrote: [...]
So I have something like this:
std::vector<boost::shared_ptr<Base> > BaseVector;
void add(boost::shared_ptr<Base>& newOne) { BaseVector.push_back(newOne); }
and I call it like this usually : boost::shared_ptr<Derived> p(new Derived); add(p);
I thought that it would work just like using raw pointers (which was working) but I get a compile time error that : no matching function call to add(boost::shared_ptr<Derived>&) canadites are add(boost::shared_ptr<Base>&).. ect.
It should fail with raw pointers, too, unless your compiler is too permissive. The problem is that
void add(boost::shared_ptr<Base>& newOne)
takes a non-const reference to shared_ptr<Base>, so you need a shared_ptr<Base> to call it. Change it to
void add(boost::shared_ptr<Base> const & newOne)
and it should work. And, as a general rule, always use a reference to const when you don't intend to modify the argument.
Peter is quite correct with the change to the argument type. It seems to me the solution could be had another way: boost::shared_ptr<Base> p(new Derived); ---- add(p); Then p is the correct type. The value being added to the vector will be a Base and not a Derived, so you loose nothing by using the shared_ptr as a Base. The only catch would be using Derived "features" between the construction of the shared pointer and the addition to the vector. ...Duane