Category: Proxy usage
Q
What else should I know about Strings?
A
The String proxy type has a lot of special support methods for dealing with string conversions between the two languages. It also comes with some implementation-based restrictions that you should be aware of:
- Don't use the same String instance to access the C++ string in two different encodings. A String instance caches the previously returned C++ string internally and will return this cached representation regardless of the requested encoding.
- For performance reasons, access to the String value cache is not synchronized. Avoid concurrent, unguarded access to the C++ string value unless you know that it has already been initialized in a previous operation, otherwise you might leak a string.
- Don't rely on implicit conversion operators in methods that take variable arguments. Take the printf() family of methods as an example:
String temp = myObj.toString();
printf( "The toString() value is: %s\n", temp );
Implicit conversion relies on the compiler being aware of the requirement to convert an object to a different type to satisfy a calling contract. In the above case, the compiler does not know that the printf() method expects a char* because that knowledge is only represented in the format string and not in the method declaration. To fix this snippet, explicitly invoke the conversion operator:
String temp = myObj.toString(); printf( "The toString() value is: %s\n", (const char*)temp );
