[osg-users] osg::observer_ptr and osg::ref_ptr
Glenn Waldron
gwaldron at gmail.com
Wed Oct 31 05:15:23 PDT 2018
Kristofer,
Yes. The semantics of observer_ptr guarantee the existence of the target
object ONLY after calling lock(). Only by calling lock() can you know for
certain that the target object exists; calling get() is insufficient
because get() will return a raw pointer that may or may not actually still
point to an existing object. Avoid observer_ptr::get() and always use the
lock() idiom.
lock() populates a true ref_ptr with the object pointer. If there were no
pre-existing references to the object, that new ref_ptr would destroy the
object when it went out of scope -- that would be unexpected and
undesirable behavior. So returning false makes sense.
I suspect that having a class creating an observer to itself is a design
flaw :)
Glenn Waldron / osgEarth
On Wed, Oct 24, 2018 at 8:59 AM Kristofer Krus <kristofer.krus at liu.se>
wrote:
> Hi Robert,
>
> Thanks. I'm having the problem that an observer_ptr that is assigned a
> pointer to an object that hasn't yet been assigned to a ref_ptr looks like
> it is invalid when I try to lock it (but not when I call the get method, so
> there is a discrepancy between observer_ptr::lock and observer_ptr::get in
> that sense). When the pointer is also assigned to a ref_ptr so that the
> reference count in the referenced object goes up, the lock method starts to
> return true instead of false.
>
> Here is what I do: In the constructor of a class that is referencable, I
> create an observer_ptr, obs, that is assigned the this-pointer—pointing at
> object A, which is the object being constructed—and I send obs to another
> object B that wants to observe A. at this point, it looks like obs is
> invalid. Directly after A has been constructed—by using the new-keyword—its
> memory address is assigned to a ref_ptr and obs.lock suddenly starts to
> succeed.
>
> Is this desirable behavior? I mean, the object exists, right? Why would
> otherwise get() succeed? Also, if you create an obs_ptr to an object
> located on the heap, that won't work as expected either when you try to
> lock it.
>
> Cheers,
> Kristofer
>
> ------------------
> Read this topic online here:
> http://forum.openscenegraph.org/viewtopic.php?p=75114#75114
>
>
>
>
>
> _______________________________________________
> osg-users mailing list
> osg-users at lists.openscenegraph.org
> http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openscenegraph.org/pipermail/osg-users-openscenegraph.org/attachments/20181031/f25dc7a8/attachment.html>
More information about the osg-users
mailing list