For convenient usage I want to write formatting function similar to sprintf just returning std::string, like this:
std::string format_string(const char* format, ...)
I can use vsnprintf there but have problem – I don’t know in advance how long temp buffer should be. On Microsoft have function _vscprintf that can do it but I think it not portable?
One option is have temp buffer start some known size then increase it if see it’s not enough with vsnprintf. Are there better approach? Thanks
P.S. Please give answer without Boost. I know about Boost, but I’m curious how implement it without.
You can use
vasprintf(), but that does an unnecessary heap allocation – it’s unlikely to be faster on average. Usingallocayou can avoid the heap. Or, you can write directly into thestringthat’s returned: NRVO should avoid a copy, and as of C++11 move semantics would limit the cost sans-NRVO to a few pointer swaps.An simpler and initially faster option would be:
The potential problem is that you’re allocating at least 256 characters however short the actual text stored: that could add up and cost you in memory/cache related performance. You might be able to work around the issue using [
shrink_to_fit]http://en.cppreference.com/w/cpp/string/basic_string/shrink_to_fit), but the Standard doesn’t require it to actually do anything (the requirements are “non binding”). If you end up having to copy to a new exactly-sized string, you might as well have used the local char array.