Kristofer Pettijohn wrote:
I'm a bit unsure about this and the results... but given the following:
...
std::string mystring;
mystring.reserve(256);
strcpy(mystring.c_str(), "Some string C-style"); // C-style copy
...
Is something like this even legal? I've tested it, and it works,
but I just don't know if its "proper".
...
No, it is not legal. It won't work for several reasons.
Firstly, in general case the pointer returned by 'c_str()' doesn't
really give you access to the innards of a 'std::string' object. In
other words, there is no guarantee that returned pointer points to the
actual character sequence controlled by this 'std::string' object. It is
possible that 'c_str()' returns a pointer to a temporary buffer
allocated specifically for this purpose. The modifications may affect
this temporary buffer, but have no effect on the actual character
sequence controlled by this 'std::string' object.
Secondly, the character sequence stored in a 'std::string' object is not
guaranteed to reside in a continuous block of memory. It can be split
across several blocks.
Thirdly, null-character has no special meaning within character sequence
stored in a 'std::string' object. 'std::string's (unlike C-strings) are
not "terminated" by any special character, which means that in one way
or another 'std::string' objects have to keep the current length of the
stored sequence as a separate piece(s) of data. For this reason, all
operations that may modify the length of the sequence must go through
'std::string's public interface, thus giving 'std::string' objects the
ability keep the length information up-to-date. Any attempts to "hack
around" that interface using, for example, direct pointers to internal
string data, will almost inevitably destroy the integrity of
'std::string' object.
--
Best regards,
Andrey Tarasevich
Brainbench C and C++ Programming MVP