Returning CORBA object references
The CORBA object symemantics are really frustrating at time. They behave close enough to how C++ does things to make them familiar, but they differ enough to lull you into a false sense of familiarity.

Your first attempt to return a reference from a method might look like this:

MyObject_var getReference() {
MyObject_var rval = new MyObject();
... // do some stuff
return rval;
};

MyObject_var tmp = getReference();

This looks promising. Let's walk through the reference count here:
  • rcount = 1 -- reference after construction
  • rcount = 2 -- reference count is incremented when assigned to the temporary used for return values.
  • rcount = 1 -- reference count is decremented when the stack variable falls out of scope.
  • rcount = 2 -- after assignment to tmp
  • rcount = 1 -- when tmp falls out of scope.
Whops! We have a dangling pointer. The reference count never returns to zero; the underlying object is never destructed.

The recommended approach is to never use _var times as parameters or return values. This avoids the dangling pointer problem and is safer. The above would be rewritten as:
MyObject_ptr getReference() {
MyObject_var rval = new MyObject();
... // do some stuff
return rval.retn();
};

MyObject_var tmp = getReference();
The reference counts in this case?
  • rcount = 1 -- reference after construction
  • rcount = 0 -- the pointer is assigned to the return value; retn releases ownership of the pointer.
  • rcount = 0 -- The var no longer owns the pointer, so the referenc count stays the same.
  • rcount = 1 -- after assignment to tmp
  • rcount = 0 -- when tmp falls out of scope.
Nice and clean, no?

Last Modified: Sunday, 26-Aug-2007 12:22:50 EDT