CORBA style was: [omniORB] CORBA::string_alloc(len) problem

Steven W. Brenneis brennes1@rjrt.com
Fri, 16 Jul 1999 09:00:17 -0400


Bjorn Wennberg wrote:
> 
> David Riddoch <djr@uk.research.att.com> writes:
> 
> > On 16 Jul 1999, Bjorn Wennberg wrote:
> >
> > > I'm just curious about this :-)
> > >
> > > As far as I'm able to understand the behaviour of string_alloc - it returns
> > > a character pointer not a new String_var class?
> > >
> > > Thus the assignment would be correct without temporary copying the String_var:
> > >
> > > 1. String_var SomeString(CORBA::string_alloc(100));
> > > 2. String_var SomeString(new char[100]);
> > > 3. String_var SomeString = CORBA::string_alloc(1000);
> > > Number 1 and 2 are equal and uses the ctor:
> > > String_var::String_var(char *p) { _data = p; }
> > > Number 3 might use either the ctor or the assignment operator, which are equal:
> > > String_var::operator = (char *p) { if (_data) string_free(_data); _data = p; }
> >
> > No - the right hand side is a String_var, not a char*, so we use:
> >
> > String_var::operator = (String_var&)
> >
> > And thus we *copy* the string rather than consume it.
> 
> I don't think so. What is the point with different ctor's if you can't use them?
> One of the ctor takes a 'char *' as parameter - and according to my debugger,
> it uses the ctor 'String_var::String_var(char *p)' when constructing the variable.
> 
> I'm not trying to be pedantic about anything - I just wanna know :-)
> 
> If the right-hand-side expression (CORBA::string_alloc(100)) returns a 'char *'
> why shall it not use the ctor that takes a 'char *'?
> 
> bjornw>

I realize this is kind of straying far from Bruce's original discussion
of copy initialization, but the basic problem with the
CORBA::String_var(char*) ctor is that it is unsafe.  First, and
foremost, C++ string literals are, by default, char*.  When the
String_var assumes the pointer and subsequently attempts to delete[] it,
you have a big problem:

CORBA::String_var something("something");

You are left with either a cast to const char* or using
CORBA::String_dup (the preferred method).  Second, using a char*
initialization without copying requires the programmer to relinquish
control of the pointer.  This makes the use of a non-const pointer
unnecessary.

I haven't delved into the code to see what happens here, but consider
this <ugly> case:

void some_fn() {
  char mychar[10];
  CORBA::String_var whatever(mychar);
}

Or to bring Bruce back into this and even worse:

void some_fn() {
  char mychar[10];
  CORBA::String_var whatever = mychar;
}

What happens in the String_var dtor?  Invoking delete[] on mychar* would
ruin your day.

Just asking.

Steve Brenneis