[osg-users] Potential bug in ref_ptr::assign

Robert Osfield robert.osfield at gmail.com
Wed Oct 25 00:40:56 PDT 2017


Hi Hartwig,

As far as I can tell the code and comment is correct, the unref afterwards
is to catch cases like:


osg::Group* parent = new osg::Group;
osg::Node* child = new osg::Geode;
parent->addChild(child);

osg::ref_ptr<osg::Node> ptr = parent; // takes a reference to pararent

ptr = parent->getChild(0); // should take a references to child and then
unref the parent deleting it


Now think what would happen if you unref first... it would delete the
parent and it's child, then you'd assign a dangling pointer.

If the compiler's optimizer is breaking this then... it's a terrible
compiler.  It does highlight how subtle ref counting can be, and how much
optimizers can't just blindly do certain types of optimization like
re-ordering.

Robert.


On 24 October 2017 at 23:34, Hartwig Wiesmann <hartwig.wiesmann at skywind.eu>
wrote:

> Hi,
>
> in ref_ptr you find the following code:
>
>
> Code:
>
>         template<class Other> void assign(const ref_ptr<Other>& rp)
>         {
>             if (_ptr==rp._ptr) return;
>             T* tmp_ptr = _ptr;
>             _ptr = rp._ptr;
>             if (_ptr) _ptr->ref();
>             // unref second to prevent any deletion of any object which
> might
>             // be referenced by the other object. i.e rp is child of the
>             // original _ptr.
>             if (tmp_ptr) tmp_ptr->unref();
>         }
>
>
>
>
> I was puzzled by the comment: actually, there is nothing that prevents an
> optimiser to re-write the code to
>
> Code:
>
>             if (tmp_ptr) tmp_ptr->unref();
>             if (_ptr) _ptr->ref();
>
>
>
>
> or
>
>
> Code:
>
>            _ptr->unref();
>             _ptr = rp._ptr;
>             if (_ptr) _ptr->ref();
>
>
>
>
> It seems to be that it has not happened, yet, respectively the scenario
> described in the comment did not occur, but this does not mean that it
> cannot happen, or?
> Actually, I do not see a solution for the described scenario, so probably
> the comment should be removed or changed? But in this case the code can be
> simplified, too.
>
> Cheers,
> Hartwig[/code]
>
> ------------------
> Read this topic online here:
> http://forum.openscenegraph.org/viewtopic.php?p=72242#72242
>
>
>
>
>
> _______________________________________________
> 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/20171025/fc964d58/attachment.html>


More information about the osg-users mailing list