What is the most simple and efficient why to copy an int to a boost/std::array?
The following seems to work, but I’m not sure if this is the most appropriate way to do it:
int r = rand();
boost::array<char, sizeof(int)> send_buf;
std::copy(reinterpret_cast<char*>(&r), reinterpret_cast<char*>(&r + sizeof(int)), &send_buf[0]);
Just for comparison, here’s the same thing with memcpy:
Your call whether an explosion of casts (and the opportunity to get them wrong) is better or worse than the C++ “sin” of using a function also present in C 😉
Personally I think
memcpyis quite a good “alarm” for this kind of operation, for the same reason that C++-style casts are a good “alarm” (easy to spot while reading, easy to search for). But you might prefer to have the same alarm for everything, in which case you can cast the arguments ofmemcpytovoid*.Btw, I might use
sizeof rfor both sizes rather thansizeof(int), but it sort of depends whether the context demands that the array “is big enough for r (which happens to be an int)” or “is the same size as an int (which r happens to be)”. Since it’s a send buffer, I guess the buffer is the size that the wire protocol demands andris supposed to match the buffer, rather than the other way around. Sosizeof(int)is probably appropriate but4orPROTOCOL_INTEGER_SIZEmight be more appropriate still.