At times I find I have a string that I know will not exceed a certain length (e.g. a file name). It seems wasteful to use a std::string for this type of thing because std::string allocates memory on the heap when it could instead be done on the stack. I'm concerned somewhat about heap fragmentation and new/delete overhead. I know certain implementations of std::string have a "small string optimization" so that small strings are actually allocated on the stack, but on VC++2005 this size is only 16 characters.
char* will work, but I'd want to guard against buffer overflow, and it does seem a bit inefficient to use O(n) strlen to retrieve string length.
I might be looking for is a template class like boost::array (http://www.boost.org/doc/html/array.html
), but I think boost::array<char, n> might not be the most suitable for strings. For example, size() will not return a value less than n, and I think I'd have to write my own safe versions of functions like strcat. Though boost::array checks for overflow, std::copy on boost::array seemed to allow overflow of the buffer without warning when I tested it. The template approach also results in generation of multiple copies of executable code if not done carefully.
No, I'm not going to use the MS safe string library (for portability reasons).
Maybe my concerns about std::string performance are not entirely warranted, but the overhead does seem avoidable. It would seem good also to avoid writing my own string library too. Maybe the Safe C String Library (http://www.zork.org/safestr/
) will do, but that uses malloc, though it does allow a custom memory allocator.
Surely someone else has already written a useful and well tested class for allocating small strings on the stack and manipulating those strings safely and efficiently(?)