Hi Remi,

On 10/6/06, Rémi Dugué <[EMAIL PROTECTED]> wrote:
Why don't you use counted reference ?
I mean :

//My class inherit osg::Reference
MyClass object1 = new MyClass ();
object1->ref();

//to delete
object1->unref();

If object1 is useless in all code and graph scene, it will be destroy.
Is it not the better way ?

Its much safer and cleaner code wise to use osg::ref_ptr<> so you above code changes into:

  {
     osg::ref_ptr<MyClass> object1 = new MyClass();  // ref( ) is do for you.
    // do your stuff
  } // ref_ptr<> is destructued and it automatically calls unref().


Why is it safer, consider changing the code to:

 void myFunction()
 {
    MyClass* object = new MyClass;
    object->ref();

    // do stuff
   if (someCondition)
   {
        return; /// ahhh memory leak,
   }

   // do more stuff
    object->unref();

 }

Wheras with  ref_ptr<>

 void myFunction()
 {
    ref_ptr<MyClass> object = new MyClass; // calls ref()

    // do stuff
   if (someCondition)
   {
        return; // ref_ptr  object  gets destructed it call unref(); no memory leak
   }

   // do more stuff

 } // ref_ptr  object  gets destructed it call unref();   no memory leak


And other variation is what happens if there in an exception, ref_ptr<> again gets cleaned up and no memory leak happens.

Now write after me:

USE ref_ptr<>USE ref_ptr<>USE ref_ptr<>USE ref_ptr<>USE ref_ptr<>USE ref_ptr<>USE ref_ptr<>

Robert :-)
_______________________________________________
osg-users mailing list
[email protected]
http://openscenegraph.net/mailman/listinfo/osg-users
http://www.openscenegraph.org/

Reply via email to