I have referred to the relevant question and other posts before this. I am also aware that std::to_string()
is the best way (but it's not available in few platforms).
While experimenting, I came across a weird issue with memcpy()
. For the example sake, assume that we always pass built-in data types (int
, char
, long
) to below function:
template<typename T>
std::string to_string (const T& value)
{
std::string s(16, 0); // Max size captured
::memcpy(&s[0], &value, sizeof(value));
return s;
}
Running this function individually in a sample program works fine. But while plugging into a bigger code base, somehow it gives weird results! i.e. it gives spurious values. (Ubuntu 14.10, g++4.9 -std=c++11)
However, if I convert the above program using sprintf()
, it works fine.
template<typename T>
std::string to_string (const T& value)
{
std::string s(16, 0); // Max size captured
s[::snprintf(&s[0], "%d", value)] = 0;
return s;
}
Question:
- Am I touching undefined behavior with
memcpy()
(or evensprintf()
)? - Would byte ordering influence this code?