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:
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:
std::string
and pre-reserve its allocation and set its size in advance (to mitigate scenario 1)std::string
around an existing char[]
(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.
In C++11 you can simply pass a pointer to the first element of the string (&str[0]
): its elements are guaranteed to be contiguous.
Previously, you can use .data()
or .c_str()
but the string is not mutable through these.
Otherwise, yes, you must perform a copy. But I wouldn't worry about this too much until profiling indicates that it's really an issue for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With