What’s the safest way for a NSString to weakly contain a const char * belonging to a std::string? Both examples below work on a simple test, in logs, and as presented in a NSTableView, but I’m concerned about strange behavior down to road. It may be the extra null character of c_str() is simply ignored (because of the length parameter passed) and either will work fine.
Given:
std::string const * stdstring = new std::string("Let's see if this works");
Then:
NSString * aStr = [[NSString alloc] initWithBytesNoCopy:
stdstring->data() length: stdstring->length()
encoding:NSUTF8StringEncoding freeWhenDone:NO];
or:
NSString * aStr2 = [[NSString alloc] initWithBytesNoCopy:
stdstring->c_str() length: stdstring->length()
encoding:NSUTF8StringEncoding freeWhenDone:NO];
or something else?
The documentation for
initWithBytesNoCopy:length:...clearly states that thelengthwill be the number of bytes used, so the null termination character will always be ignored. Hence the contents of the memory returned bydata()andc_str()is equally suitable.With that in mind:
The lifetime guarantees of the memory returned by
std::string‘sdata()andc_str()functions are identical – they will survive until you call a non-const member function on the string object. It depends on the implementation whether the internal data structure is already a null-terminated character array, so in general,data()will be cheaper or identical in complexity toc_str(). I’d therefore go fordata().