Strings have always been a source of confusion. The CORBA standard adopts a not necessarily intuitive mapping for strings for the C++ language. The following description is partially taken from chapter [16.7] in the CORBA 2.2 specification.
As in the C mapping, the OMG IDL string type, whether bounded or unbounded, is mapped to char* in C++. String data is null-terminated. In addition, the CORBA module defines a class String_var that contains a char* value and automatically frees the pointer when a String_var object is deallocated. When a String_var is constructed or assigned from a char*, the char* is consumed and thus the string data may no longer be accessed through it by the caller. Assignment or construction from a const char* or from another String_var causes a copy. The String_var class also provides operations to convert to and from char* values, as well as subscripting operations to access characters within the string. The full definition of the String_var interface is given in appendix C-2 of the CORBA 2.2 specification.
For dynamic allocation of strings, compliant programs must use the following functions from the CORBA namespace:
// C++ namespace CORBA { char *string_alloc( ULong len ); char *string_dup( const char* ); void string_free( char * ); ... }
The string_alloc function dynamically allocates a string, or returns a null pointer if it cannot perform the allocation. It allocates len+1 characters so that the resulting string has enough space to hold a trailing NULL character. The string_dup function dynamically allocates enough space to hold a copy of its string argument, including the NULL character, copies its string argument into that memory, and returns a pointer to the new string. If allocation fails, a null pointer is returned. The string_free function deallocates a string that was allocated with string_alloc or string_dup. Passing a null pointer to string_free is acceptable and results in no action being performed.
Note that a static array of char in C++ decays to a char*, so care must be taken when assigning one to a String_var, since the String_var will assume the pointer points to data allocated via string_alloc and thus will eventually attempt to string_free it:
// C++ // The following is an error, since the char* should point to // data allocated via string_alloc so it can be consumed String_var s = "static string"; // error // The following are OK, since const char* are copied, // not consumed const char* sp = "static string"; s = sp; s = (const char*)"static string too";
See the directory mico/test/idl/5 for some examples on how to use strings in conjunction with operations.