Using ofPtr with std::tr1::enable_shared_from_this

I’m writing some Gui code where I have a load of Widget objects managed by ofPtr. I want a method on a widget to be able to set a field on another widget to be an ofPtr to itself. Which left me wanting to get an ofPtr to this, without creating duplicate pointers to the same object with their own ref counts leading to a double free.

Googling for a solution I found std::tr::enable_shared_from_this which does what I want with std::tr::shared_ptr, which ofPtr sub classes. So I have:

class Widget;  
typedef ofPtr<Widget> WidgetPtr;  
class Widget : public tr1::enable_shared_from_this<Widget> {  
		virtual ~Widget() {}  
		WidgetPtr getPtr() { return (WidgetPtr)shared_from_this(); }  

Which fails because it cant convert from a std::tr1::shared_pointer to an ofPtr:

../../../libs/openFrameworks/types/ofTypes.h:102:7: note:   no known conversion for argument 1 from ‘std::tr1::shared_ptr<ofxPg::Widget>’ to ‘const ofPtr<ofxPg::Widget>&’  

I was hoping this might work as ofPtr is a subclass and I’m starting to get that special pointers headache!
Anyone any ideas how to fix this? If the conversion is possible should we patch ofPtr to make it work?


I didn’t realize that ofPtr wasn’t just shared_ptr until I saw this, and the only extra functionality I can see is dynamic_pointer_cast, which I’m not sure is worth the loss of compatibility with shared_ptr. Being able to use enable_shared_from_this is pretty nifty and I think we could get the dynamic_pointer_cast functionality in a static utils method.

Just realised that ofPtr is likely a sub-class because you can’t typedef a templated class (until C++11). So I’m guessing that ofPtr is trying to get around this using a subclass.

(btw Joshua, I posted to of-dev about this and the mail looks sent but I’m not seeing it on the list. Have you seen a post from me today in dev?)

yes your post arrived in of-dev, it just doesn’t get bounced back to you (which I find pretty smart). You can always check the archives: