I've been very satisfied with my String_ref class, which represents a non-owning reference to a string (something similar to boost::string_ref, llvm::StringRef or StringPiece), but I've soon realized that there's still one important piece missing in the puzzle. That piece is a stack-allocated string, or if you like, a fixed-size string buffer (String_buf), which would allow me to get rid of all the unnecessary heap allocations when composing (formatting) temporary strings on the stack or storing strings of a known maximum size as class members.

After a bit of googling, I've come across an interesting approach by Chromium that offers a possible solution. Namely, it's their stack_container.h, which is a custom STLallocator that allocates memory on the stack rather than on the heap. This particular implementation has a very nice ability to overflow onto the heap when the initial fixed size is exceeded - very nice and safe indeed!

Side note: I'm really happy that I don't use std::string in my interfaces any more. In this particular case the problem is that two std::strings parametrized by different STL allocators are actually two completely different types. So a string needs to get converted (copied) each time it crosses interface boundaries (even though it is passed by a const reference) . The use of String_ref in the interfaces solves this problems as the translation between different string representations is trivial!

Although a stack allocator seems attractive, I've decided to go with a custom fixed-size string buffer (String_buf) for now, mainly due to the fact that it's easily implementable using std::array. Here's a possible implementation, with a very convenient printf-like format() functionality: