Using ReferenceCountedObjetPtr<X> for return values in function/method declarations instead of naked X*

My app makes use of reference counting throughout.

if is there any point in writing     ReferenceCountedObjetPtr<X> foo (); 

instead of just  X* foo();  

  Of course this pointer will be used in an assignment to some ReferenceCountedObjetPtr in the code.

 

It seem wasteful to be instantiating ReferenceCountedObjetPtr<X> briefly, having the target class refcount incremented, only to straight away

have the refcount decrementes as the ReferenceCountedObjetPtr<X>  return value goes out of scope.

 

cheers

The compiler will often be able to optimise-away the temporary objects, so there may be little or no overhead.

The danger in returning a raw pointer is that if you write something like this:

Thing* getThing()
{
    ReferenceCountedObjectPtr<Thing> t = new Thing();

    ...

    return t;
}

..then you'll be returning a dangling pointer, and this is an easy mistake to make.

In case: ( http://www.aristeia.com/Papers/resourceReturnProblem.txt ).

thanks for that.

 

As the code in question is auto generated by my cross-compiler I can assure that the pointer from such a function does always go into a  ReferenceCountedObjectPtr<Thing>  at the other end - all my class instances are references and local variables are always ReferenceCountedObjectPtr<Thing>  too. So i should be ok in that situation shouldnt i ? 

 

so for example with 

Thing* getThing() {

 ReferenceCountedObjectPtr<Thing> t = new Thing(); 
... 
return t; 

}

i might have code like: 

 

void fooThing() {

  ReferenceCountedObjectPtr<Thing> t = getThing();
   ...
   ...
   ...

}




 

 

 

is that ok ? 

 

Working in Xcode it does seem that - in debugger mode at least I have to step through the reference countpointer stuff for the return value - so 

even if the compiler strips out this code in the final build its a little of a drag when stepping thru the debugger.

 

..not sure you fully understood what I meant in my previous post?

It rarely matters what happens to the pointer that is returned - there's not much damage you can do with that. The danger is that in the code-snippet I posted, it deletes the object inside the function, and then returns a dangling pointer.

eek  yes !   got you.