|
Boost Users : |
From: Sam Partington (Sam.Partington_at_[hidden])
Date: 2003-06-23 09:48:44
This is normal behaviour for a pointer too, so shared_ptr is correct to
disallow this :
void AddObject(CBase&* pObj);
...
CDerived* pDerived = 0;.
AddObject(p); // also won't compile
If you think about it this makes sense. Imagine, if that behaviour were
allowed this would cause some problems:
class CDerived2 : public CBase {};
void AddObject(CBase&* pObj)
{
pObj = new CDerived2;
}
...
CDerived* pDerived = 0;
AddObject(pDerived); // eeek! pDerived now points to a CDerived2
object!
Normally in this situation I would return a shared_ptr<> rather than take
one by reference. (I prefer that style anyway, but lets not get into that
:-) ). You will then have to do a cast to the derived object ptr:
BasePtr AddObject();
...
BasePtr p = AddObject();
if (DerivedPtr pDerived = shared_dynamic_cast<CDerived>(p))
{
// ...
}
HTH
Sam
Drew wrote:
> To be a little more detailed, here is what I am trying to accomplish:
>
> typedef boost::shared_ptr<CBase> BasePtr;
> typedef boost::shared_ptr<CDerived> DerivedPtr;
>
> AddObject(pBase); // works
> AddObject(pDerived); // does not work
>
> void AddObject(BasePtr& pObj)
> {
> std::vector<BasePtr>::iterator pos = find(myList.begin(),
> myList.end(), 5);
>
> if (pos != myList.end()) {
> pObj= *pos;
> }
> else {
> myList.push_back(pObj);
> }
> }
>
> error C2664: 'Fn' : cannot convert parameter 1 from 'DerivedPtr'
> to 'ParentPtr &'
> A reference that is not to 'const' cannot be bound to a non-lvalue
>
> However,
>
> AddObject(base); // works
> AddObject(derived); // works
>
> void AddObject(CBase& base)
> {
> }
>
> This is a generic function that adds an element if it does not exist.
>
> Why when I use a shared_ptr does this not work?
>
> I dont want a specific lookup for all of my objects.
>
> Thanks guys...
>
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net