Quote:Original post by bkt
But that doesn't seem to be liking me too much. I'll fiddle around with a little bit more, but from what I'm gathering, the ampersand operator doesn't return a pointer to the object inside the shared_ptr?
Nope, it's getting the addrses of the shared_ptr structure itself (similarly, using the ampersand operator on a pointer would get a pointer to a pointer, not return the original pointer). Use the .get() member to get a raw pointer. Note: Constructing a second shared_ptr from that raw pointer will in fact cause the item to be deleted twice!!! So don't do this:
boost::shared_ptr< foo > foo1( new foo );boost::shared_ptr< foo > foo2( foo1.get() ); //ERROR: We'll delete foo twice!!!
Or do so indirectly using casts.
I'm curious as to the types of m_pTimer, m_pVideo, and m_pLogic are. If they are of types that derive from ITask, then there's no need to do any casting jumbo:
struct ITask {};struct TimerTask : public ITask {};boost::shared_ptr< TimerTask > m_pTimer( new TimerTask );boost::shared_ptr< ITask > foo( m_pTimer );
For 3 of the 4 _cast<> operators, there is a boost equivilant. Let's assume we want to use dynamic_cast to ensure a pointer to an ITask is in fact a TimerTask. We could write:
boost::shared_ptr< ITask > foo( ... );boost::shared_ptr< TimerTask > Timer( dynamic_cast< TimerTask * >( foo.get() ) );
This would be bad, as we would have constructed Timer from a raw pointer (causing the double delete problem originally outlined). The alternative:
boost::shared_ptr< ITask > foo( ... );boost::shared_ptr< TimerTask > Timer( boost::dynamic_pointer_cast< TimerTask >( foo ) );
This code will not delete our task twice, and will in fact function as expected.
The full list of casts available are:
static_cast< T * > -> boost::static_pointer_cast< T >const_cast< T * > -> boost::const_pointer_cast< T >dynamic_cast< T * > -> boost::dynamic_pointer_cast< T >
More Documentation