I should preface this question by saying I think the answer is probably no, but I'd like to see what other people think about the issue.
I spend most of my time writing C++ that interacts with the Win32 API which like most C style APIs wants to either:
- Take buffers which I've provided and operate on them.
- Or return pointers to buffers which I need to later free.
Both of these scenarios essentially mean that if you want to use std::string
in your code you've got to accept the fact that you're going to be doing a lot of string copying every time you construct a std::string
from a temporary buffer.
What would be nice would be:
- To be able to allow C style APIs to safely directly mutate a
std::string
and pre-reserve its allocation and set its size in advance (to mitigate scenario 1) - To be able to wrap a
std::string
around an existingchar[]
(to mitigate scenario 2)
Is there a nice way to do either of these, or should I just accept that there's an inherent cost in using std::string
with old school APIs? It looks like scenario 1 would be particularly tricky because std::string
has a short string optimisation whereby its buffer could either be on the stack or the heap depending on its size.