The StaticString library is pretty easy to use, however there’s a couple of little gotchas and interesting points.

The first is copying!

Copying StaticStrings

C-strings are just pointers to character arrays. Creating a new char pointer to the string, of course, will only ‘shallow-copy’.

Modifying c_s2 will also modify c_s1 because they are both pointing to the same address in memory.

StaticStrings can only deep-copy.

Every byte (up to and including the null terminator at s1[6] ) is copied from s1 to s2.

When C-strings are passed as functions parameters it’s only a pointer that is passed.

And when StaticStrings are passed as parameters they are, of course, deep-copied.

By passing ss to foo, a whole new StaticString is created and ss is deep-copied to it. This means at least an extra 24 bytes is added to the stack, and every byte (up to the null terminator) from ss is copied to this new space. It’s a lot more efficient to simply pass a reference like this

Reference passing only pushes a handful of extra bytes (usually around four) onto the stack and no bytes are copied. This is a lot more efficient, so where possible use references to pass strings.

Now let’s say we’ve got strings of different sizes. We’re copying type etk::StaticString<20> to etk::StaticString<80>. Normally that would lead to compiler errors, but StaticString overloads the cast operator to perform a deep copy. This means StaticStrings of different maximum lengths can be used seamlessly together.

UNTIL you start trying to pass references. This example won’t compile . . .

If you really would prefer to pass references to and from strings of any length, you must use templates or the auto specifier.

or using C++11

Using StaticString With Other Libraries

More than likely you’ll need to use StaticStrings with other libraries. You can get a constant pointer to a C string using the c_str() function.

If you need to actually modify the StaticString from a pointer, there is the raw_memory() function that returns a char*. It’s far better to use the array access operators, though, since they protect against buffer overruns.


Leave a Reply

Your email address will not be published. Required fields are marked *