CORBA can pass references to objects as parameters and return values of operations. It is important to understand the mapping of object references and how to acquire an object reference. In C++, object references of type StockPortfolio, for example, are mapped to variables of type StockPortfolio_ptr
and StockPortfolio_var
.
StockPortfolio_ptr
is the fundamental object reference type. A variable of this type behaves like a pointer, and the object it references can be invoked using the -> operator.
Note: A variable of type CORBA::Object_ptr
or CORBA::Object_var
can reference any CORBA object.
Each CORBA object has a reference count indicating the number of local references that refer to it. This reference count is incremented when a new local reference to the object is created and decremented when a local reference to the object is deleted. Once an object's reference count falls to zero, it is deallocated automatically.
When assigning two object references of type StockPortfolio_ptr
, you must explicitly increment the reference count:
StockPortfolio_ptr sp1 = ...; StockPortfolio_ptr sp2; sp2 = StockPortfolio::_duplicate(sp1);
When you create a class, the IDL compiler automatically adds the function StockPortfolio::_duplicate( )
to the class.
If you make the following assignment
sp2 = sp1;
the two object references will refer to the same object, but the object's reference count will not be incremented. The number of pointers to the object will not be reflected in its reference count. Such assignments can be made and their lightweight nature is sometimes useful, but you must be careful, for example, not to decrement the reference count using one pointer and then access the target object using the other.
Reference counts are decremented through calls to CORBA::release( )
. For example:
StockPortfolio_ptr sp1; StockPortfolio_ptr sp2; sp2 = StockPortfolio::_duplicate(sp1); ... ... CORBA::release(sp2); CORBA::release(sp1);
If the initialization of sp1
created the target object, that object will be released when CORBA::release(sp1)
is released.
If CORBA::release(sp2)
is not called, the count on the referenced object would be incorrect after the execution of the inner statement sequence. Similarly, CORBA::release(sp1)
must be called to return the object's reference count to its original value after the full code fragment has been executed.
Note: Do not delete an object by executing the following:
delete p1; // This is an Error.