Cysneros, Nelson A CIV SPAWAR SSC PAC, 56510 wrote:
So sorry if this is a way too obvious question but what is the difference between observer_ptr and ref_ptr? And when would you use one over the other? osg::observer_ptr : Smart pointer for observed objects, that automatically set pointers to them to null when they deleted osg::ref_ptr : Smart pointer for handling referenced counted objects They seem to do the same thing. At least I was able to replace all observer_ptr with ref_ptr and the example still compiled and ran.

They're quite different, actually. When a ref_ptr is assigned the address of an object, it increases the reference count on the object. Likewise, when it is detached from the object (either by deleting the ref_ptr, letting it go out of scope, or assigning it a different address), the reference count on the first object is decreased. Whenever a Referenced object's reference count drops to zero, the object is deleted.

observer_ptr never changes the reference count of the object to which it points. The main benefit of an observer_ptr is that when the pointed object is deleted, the value of the observer_ptr is automatically set to NULL.


For example:


observer_ptr<Node>   nodeObs;
ref_ptr<Node>        nodeRef;


nodeRef = new Node();      // Node's ref count is now one
nodeObs = nodeRef.get();   // Node's ref count is still one

nodePtr = NULL;            // Node's ref count is now zero, and is deleted
                          // nodeObs is now NULL


OK, not a great example, but hopefully you get the idea  ;-)

--"J"
_______________________________________________
osg-users mailing list
[email protected]
http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org

Reply via email to