I have a question very similar to
How do I allocate a std::string on the stack using glibc's string implementation?
but I think it's worth asking again.
I want an std::string
with local storage that overflows into the free store. std::basic_string
provides an allocator as a template parameter, so it seems like the thing to do is to write an allocator with local storage and use it to parameterize the basic_string
, like so:
std::basic_string<
char,
std::char_traits<char>,
inline_allocator<char, 10>
>
x("test");
I tried to write the inline_allocator
class that would work the way you'd expect: it reserves 10 bytes for storage, and if the basic_string
needs more than 10 bytes, then it calls ::operator new()
. I couldn't get it to work. In the course of executing the above line of code, my GCC 4.5 standard string library calls the copy constructor for inline_allocator
4 times. It's not clear to me that there's a sensible way to write the copy constructor for inline_allocator
.
In the other StackOverflow thread, Eric Melski provided this link to a class in Chromium:
http://src.chromium.org/svn/trunk/src/base/stack_container.h
which is interesting, but it's not a drop-in replacement for std::string
, because it wraps the std::basic_string
in a container so that you have to call an overloaded operator->()
to get at the std::basic_string
.
I can't find any other solutions to this problem. Could it be that there is no good solution? And if that's true, then are the std::basic_string
and std::allocator
concepts badly flawed? I mean, it seems like this should be a very basic and simple use case for std::basic_string
and std::allocator
. I suppose the std::allocator
concept is designed primarily for pools, but I think it ought to cover this as well.
It seems like the rvalue-reference move semantics in C++0x might make it possible to write inline_allocator
, if the string library is re-written so that basic_string
uses the move constructor of its allocator instead of the copy constructor. Does anyone know what the prospect is for that outcome?
My application needs to construct a million tiny ASCII strings per second, so I ended up writing my own fixed-length string class based on Boost.Array
, which works fine, but this is still bothering me.