Reputation: 4076
My question arises from reading a comment of function length() and size() in basic_string.h of libstdc++, that is distributed with Ubuntu 14.04:
The comment states the following:
Returns the number of characters in the string, not including any null-termination.
This comment to me is confusion in the case where strings only contains null terminating characters, especially when considering how strlen works traditionally, and I am concerned that compilers might implement strings in a way where they don't return the size() but the length as determined by char_traits::length().
Whilst it might obvious that a string length is known without requiring null terminating characters, the notion of the length of a traditional string is not the same as that of a container. I feared that this might have changed at some point, and I'm wondering at the risk of code like the code below ...
std::string header(4, char{});
assert(header.length() == 4);
... not being entirely cross platform.
I'm assuming it (the question) must hold valid, and my assumption is from this reference:
Upvotes: 1
Views: 79
Reputation: 171383
where strings only contains null terminating characters
Those are not "null terminated characters", since they don't terminate the string, they are part of it. They are null characters, but not null terminated.
The behaviour you see is guaranteed by the standard. You told the string
to create a string of four null characters, so that's what you get.
That would be a ridiculous thing to be non-portable between compilers, or between revisions of the standard. It's always been guaranteed.
My question also arises because this is inconsistent with the traditional behavior of strlen, and char_traits::length()
That's irrelevant, because a char*
doesn't know its length. A std::string
does.
I'll change the comment in the libstdc++ header that confused you to make it clearer.
Upvotes: 3