A point not made by others is:
I think this is unsafe for Non-POD types. Oddly enough, adding initialization to the constructor makes it unnecessary. So I suggest a freestanding function that checks POD-natic statically (the sample uses C ++ 0x type_traits , but you can also use Boost)
#include <iostream> #include <type_traits> template <typename T> typename std::enable_if<std::is_pod<T>::value>::type* FeedFace(T& v) { static const unsigned char MAGIC[] = { 0xFE, 0xED, 0xFA, 0xCE }; unsigned char *me = reinterpret_cast<unsigned char *>(&v); for( size_t ii = 0; ii < sizeof(T)/sizeof(unsigned char); ++ii ) me[ii] = MAGIC[ii % sizeof(MAGIC)/sizeof(unsigned char)]; } struct Pod { char data[37]; }; struct NonPod : Pod { virtual ~NonPod() { } }; int main() { Pod pod; FeedFace(pod); NonPod nonpod; // FeedFace(nonpod); // fails to compile (no matching function call) return 0; }
source share