I was looking at a way to achieve sprintf() functionality with std::string and I found a good answer from std::string formatting like sprintf. This is somewhat hacky though because it writes directly to the pointer returned from string.c_str(). So I reimplemented it using a char * with malloc() and realloc().
std::string string_format(const char * format, ...) { size_t size; size_t n; va_list args; char * buffer; std::string str; size = 100; buffer = malloc(size); for (;;) { va_start(args, format); n = vsnprintf(buffer, size, format, args); va_end(args); if (n > -1) { if (n < size) { size = n; break; } size = n + 1; } else { size *= 2; } buffer = realloc(buffer, size); } str = std::string(buffer, size); free(buffer); return str; } I know I could just do:
str = std::string(buffer); But then it will have to essentially do strlen(buffer). I could make it a little better by:
str = std::string(buffer, size); But would using string.swap() be more efficient by swapping the internal buffer instead of copying it?
str.swap(std::string(buffer, size)); Is there a better way to do this?
&str[0]in C++11 as long as you stop before the null, and don't touch the null at all.swapwill be more efficient unless you prove otherwise by posting profiling data for both the cases. And If you are really serious about this being a bottle neck then you should be doing that.