Boost logo

Boost :

From: James Slaughter (James_at_[hidden])
Date: 2001-04-14 18:22:01


I was recently investigating the performance of some code which made
heavy use of comparisons between std::string's and plain char*'s, when I
noticed that almost every operation required the length of the string.
When comparing a c-style string multiple times, it would be more
efficient to evaluate the length just once and for simple equality it's
often faster to compare the lengths of the strings before checking the
actual content. However, copying the char* to a std::string purely to
cache the length involves a potentially expensive allocation.

After a little thought, I realised that what I was actually looking for
was a basic_string-like wrapper for char*, with overloaded operators for
comparison between the two types. The natural interface for such a beast
would be the same as a basic_string, save for operations which change
the length, and a few extra members for changing the content to a new
pointer. Since it would be useful for more than just performance, I'd be
very surprised if someone hasn't already done this, but a glance at the
boost libraries didn't reveal anything.

Another use of the class would be for efficiently manipulating just a
fragment from a larger string, such as part of the header in an HTTP
request. I would have a lot of use for this, but it does pose a very
minor problem: c_str could not be implemented without making a copy,
because the strings would require null termination. That's not a problem
for me, but it would be very easy to provide both a basic_cstring and a
basic_cstring_fragment. We would need to consider whether code using
std::strings is likely to be parameterised to also accept cstrings, and
if so, whether c_str() is likely to be more useful than data().

Note that a fragment is not a "complete" string because it can't provide
c_str, and that a "complete" string is not a fragment because it
wouldn't support resetting content with an explicit length. However, the
two versions could easily share code from a detail::basic_cstring_base.

Has this already been done? If so, where? If not, would anyone be
interested if I were to submit one?

Best Regards,

Boost list run by bdawes at, gregod at, cpdaniel at, john at