Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you avoid using temporary buffers when using std::string to interact with C style APIs?

Tags:

c++

c

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:

  1. Take buffers which I've provided and operate on them.
  2. 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:

  1. 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)
  2. To be able to wrap a 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.

like image 946
Benj Avatar asked Oct 14 '11 09:10

Benj


1 Answers

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.

like image 73
Lightness Races in Orbit Avatar answered Nov 08 '22 06:11

Lightness Races in Orbit