I have a big concern with this code. It uses local static variables, so this will result in race conditions if used in a multithreaded program.
I assume you did that to improve performance? Constructing the std::stringstream
could potentially incur some overhead. So having that variable as a static would be understandable if you are sure no race conditions apply. But the str
string certainly doesn't have to be a local static. Actually, it is not needed at all, since stringstream::str()
exists.
I think you have two options here:
Make it thread-safe and cleaner at the cost of some extra object construction every call, which is probably not a big deal:
std::string to_string(int val) {
std::stringstream ss;
ss << val;
return ss.str();
}
Or, if you need ultimate performance and cannot afford the chance of a memory allocation by std::stringstream
, then you could use sprintf
, snprintf
or itoa
. This is a possible implementation, also thread safe, with no statics:
std::string to_string(int val) {
// Buffer size is arbitrary in this example. Could be smaller.
// 128 is more than enough for any integer number.
char buffer[128];
std::snprintf(buffer, sizeof(buffer), "%i", val);
return buffer;
}
I suggest going with the first one, but if you have a justifiable performance concern, then the second one should perform slightly better.
operator<<
define. So if you make this a template function it should work with all types. Boost did something like this withboost::lexical_cast<>()
\$\endgroup\$