So
Code:
* A string looks like this:
*
* @code
* [_Rep]
* _M_length
* [basic_string<char_type>] _M_capacity
* _M_dataplus _M_refcount
* _M_p ----------------> unnamed array of char_type
* @endcode
*
* Where the _M_p points to the first character in the string
........................
* The reason you want _M_data pointing to the character array and
* not the _Rep is so that the debugger can see the string
* contents.
and later on
Code:
data() const { return _M_data(); }
............
_M_data() const { return _M_dataplus._M_p; }
_CharT* _M_p; // The actual data.
So I am guessing that data() returns a pointer to the first character of the string, always. That is after everything else. Since you can read those data, you can as well change them.
If you do this
Code:
char* buf = const_cast<char*>(str.data());
you should have buf = str._M_p. If the string re-allocates memory it would do something like
Code:
str._M_p = realloc(....);
sto wouldn't
still modify the first character of the string??
If you later do
it will reallocate memory and copy the values. Again won't buf be pointing at _M_p, thus at the internal buffer?
I am reading about reference counting, so I get what CornedBee meant. I guess it becomes troublesome