Re: std::string and C APIs
On Feb 22, 12:19 am, Early Ehlinger
<spamsink.early.spams...@respower.com> wrote:
I'm calling a C API that expects a char* and a buffer size for output,
like so:
int c_style_api( char* output_buffer , int output_buffer_size );
I'm trying to wrap it in a more C++-ish manner for a function signature
that looks like this:
std::string cpp_wrapper( );
My current approach is not something I'm particularly fond of:
std::string cpp_wrapper( ) {
int size = calculate_size( );
std::vector< char > buffer( size );
int check = c_style_api( &*buffer.begin() , size );
throw_on_error( check );
std::string result( buffer.begin() , buffer.end() );
return result;
I'd just have
return std::string( buffer.begin() , buffer.end() );
but that's just nitpicking, simplyfing the code but not really
enhancing performance.
}
The copy during the constructor of "result." bothers me, mainly because
there is strong likelihood that cpp_wrapper will be called repeatedly in
a critical loop.
You should always measure before complaining abot performance.
I'm also concerned that std::vector's constructor may be initializing
the buffer, but I'm hoping to find a way to eliminate the vector
altogether anyway.
It will.
Others have recommended that you use a std::string directly, passing
&*string.begin() to the buffer. Currently this is undefined behaviour
as the std::string buffer is not required to be contiguous, but in
practice you'll be safe. No known std::strings use non-contiguous
buffers, and since the new C++ standard will likely require the string
to be continuous (as it is required by std::vector), no std::string
implementation is likely to ever break your code.
/Peter
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]