[omniORB] Sequences/allocbuf/freebuf comment

Glenn A. Hochberg gah@research.att.com
Thu, 15 Feb 2001 18:46:42 -0500

Yan Pujante wrote:

> Hello
> I am not sure it is the right place for this kind of comment but here it is. I
> am using a sequence of structures (in IDL: typedef sequence<C> CSeq;)

> [...]

> C *array = CSeq::allocbuf(n);
> // initialize each element of the array...
> // this can potentially throws an exception
> // here I am giving the ownership of the array to the sequence
> // so I don't have to free it myself
> CSeq_var seq = new CSeq(n, n, array, true);
> return seq._retn();
> The problem in this code is that it can potentially leak memory if something
> wrong happen between allocbuf and the transfer of ownership.

I think a simpler way to accomplish the same thing would be to let the sequence
manage the memory for you from start to finish, and use the sequence member
functions to initialize the data, e.g.:

CSeq_var seq = new CSeq(n);    // allocates a sequence with enough room for n
seq->length(n);    // set length
// initialize each member using accessor
for (CORBA::ULong i = 0; i < n; i++) {
    (*seq)[i].foo = a;
    (*seq)[i].bar = b;
return seq._retn();

Henning & Vinoski's book (Advanced CORBA Programming with C++) recommends avoiding
the sequence data constructor (the one where you allocate the buffer yourself)
particularly for sequences of complex data types.

Glenn A. Hochberg     | "Any activity becomes creative when the doer
AT&T Labs             |  cares about doing it right, or doing it better."
gah@research.att.com  |      -John Updike