How should smart pointers be used?

Smart pointers handle casting, and if not, is there a safe way to get around this limitation?

An example of what I'm trying to do is to have two STL vectors (for example) containing smart pointers. The first contains smart pointers to the base class, and the second contains smart pointers to the derived class. Smart pointers refer to counting, for example. similar behavior for Boost shared_ptrs, but manual rolling. I included some sample code that I whipped to give an example:

vector<CBaseSmartPtr> vecBase;
vector<CDerivedSmartPtr> vecDer;
...
CBaseSmartPtr first = vecBase.front();
vecDer.push_back(CDerivedSmartPtr(dynamic_cast<CDerived*>(first.get()));

It seems to me that it is not safe, since I think that I have two smart pointers that manage the same object. At some point down the track, this is likely to cause one of them to free the object, while the other still contains references to it.

What I hope for, but don't think it works, is a direct listing, keeping the same object, for example.

dynamic_cast<CDerivedSmartPtr>(first)

Should I look for a second container to use only CBaseSmartPtr and downcast when used? Are there other solutions?

+5
source share
5 answers

downcasting, . const-correctness in ( , ). .

, , - . smart_ptr<Base> smart_ptr<Derived>, . , . - size_t, , . (: , )

. , smart_ptr smart_ptr. ctor static_cast<T*>((U*)0);. , , T U ( const).

. T, smart_ptr<T> smart_ptr<Base1_of_T>, smart_ptr<Base2_of_T>, ... , a dynamic_cast<smart_ptr<T> > . smart_dynamic_cast<SPT>(smart_ptr<U> const& pU). , SPT. return SPT(dynamic_cast<SPT::value_type*>(&*pU)).

+5

, , - . , D isa B, smartptr<D> isa smartptr<B>. , ++, , , /.

http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/pointer_cast.html , boost:: smart_ptr. , Boost.

+2

. , boost:: shared_ptr.

+1

, std::auto_ptr, STL, - , , STL , . - boost::shared_ptr, , , . , .

0

Microsoft:

    std::shared_ptr<base> sp0(new derived); 
    std::shared_ptr<derived> sp1 = 
    std::dynamic_pointer_cast<derived>(sp0); 
0

All Articles