Comparing empty strings where ' string = "" '

This is something that I've always been curious about but was never sure how to ask.

I've always thought of strings as just dynamic arrays plus encapsulation. So when I set a string to the value "". What am I actually setting it to?

Am I setting it to a ptr which points to NULL. Or am I setting it to the value of just the terminating character '\0'. In other words, what is contained inside a string of value "". And is there maybe a special case for it when comparing strings (I.E. string1 == string2). Like if a "" string was a NULL, there would definitely be a special case for it.
Inside the string object are various member variables. One of them is a char*, pointing to the start of an array of char in which the letters of the string are stored. Another variable is a number keeping track of the number of letters in the char array.

The char* points to the start of that char array, and effectively never changes. Why would it ever change? (Barring the need to reallocate that char array for more capacity)

When you set the string to "", the first element of the char array is set to zero, and the number keeping track of the number of letters is set to zero. The char* doesn't change and never gets set to NULL.
I don't think the implementation is not allowed to set its internal pointer to nullptr when std::string::size() == 0.
I don't think the implementation is not allowed to set its internal pointer to nullptr when std::string::size() == 0.


By this I think you're saying that if it really wanted to, it could set its "internal pointer" to nullptr when the size becomes zero. There's nothing that explicitly forbids it.

This is true, in as much as the string can have some "internal pointer" as part of its implementation and the standard doesn't care what it does with this "internal pointer" of which you speak.

It would seem odd to have such a thing, though, because even when the size is zero, c_str() still has to return a valid pointer (i.e. not a nullptr), so whatever this "internal pointer" of which you speak is that's happily a nullptr, there doesn't seem to be any benefit to making it a nullptr and I don't know what it's used for.
Last edited on
That requirement can be satisfied by having both some_string.c_str() and some_string[0] return a pointer and reference to a static char if some_string.size() == 0.
It can be, but in my experience it isn't. Where we are now is the boundary between ways we could implement a C++, and how it is (in my practical experience) implemented.
Topic archived. No new replies allowed.