I have a codebase with some ubiquitous data structure; and said structure has an std::string member. Now, for reasons, I want this codebase to work when std::string is unavailable, and in fact with no dynamic allocation of memory (at least not the usual way). I can also verify that that string member never has a string longer than M characters (and M is small).
Now, what should I replace std::string with, so that I don't have to do a lot of rewriting, on one hand; and that my constraints are satisfied on the other?
Note:
- I can't move the computation of the string to compile-time.
- It's ok if the solution only has a trivial constructor, a
const char*
constructor, or both. - Solutions involving the use of
std::string_view
may be relevant (but I'm not sure whether that would be useful).
char[M + 1]
would probably be a decent, simple option to investigate. The amount of rewriting may be more or less depending on how you have used the string member so far.If the "std::stringiness" of the member is used a lot, then you could possibly reduce the amount of rewrite by implementing a custom class that offers similar interface as
std::string
, but internally useschar[M + 1]
.boost::static_string
mentioned by Drew Dormann is a template for such class.P.S. If you can still use
std::string
and are only restricted from using dynamic memory, then you could potentially keep usingstd::string
with a custom allocator instead, as mentioned by Galik.