int main(void)
{
std::string foo("foo");
}
My understanding is that the above code uses the default allocator to call new. So even though the std::string foo is allocated on the stack the internal buffer inside of foo is allocated on the heap.
How can I create a string that is allocated entirely on the stack?
I wanted to do just this myself recently and found the following code illuminating:
It defines a new std::allocator
which can provide stack-based allocation for the initial allocation of storage for STL containers. I wound up finding a different way to solve my particular problem, so I didn't actually use the code myself, but perhaps it will be useful to you. Do be sure to read the comments in the code regarding usage and caveats.
To those who have questioned the utility and sanity of doing this, consider:
Some people have commented that a string that uses stack-based allocation will not be a std::string
as if this somehow diminishes its utility. True, you can't use the two interchangeably, so you won't be able to pass your stackstring
to functions expecting a std::string
. But (if you do it right), you will be able to use all the same member functions on your stackstring
that you use now on std::string
, like find_first_of()
, append()
, etc. begin()
and end()
will still work fine, so you'll be able to use many of the STL algorithms. Sure, it won't be std::string
in the strictest sense, but it will still be a "string" in the practical sense, and it will still be quite useful.