4 ms·
char* is universal memory format, you could specialize from that into anything you want
by Iwan-Zotow 7y ago
char* is universal memory format, you could specialize from that into anything you want
- MauranKilom 7y agoThat's not how the C++ object model works. Objects in C++ have clearly defined lifetimes. If you reinterpret_cast<int* >(someCharBuffer) and then dereference that, you have Undefined Behavior unless an int object is alive at that exact location. You can do int value[2] = {0, 0}; char* ptr = reinterpret_cast<char*>(value) + sizeof(int); (*reinterpret_cast<int*>(ptr))++; or (given knowledge about compiler padding): struct XY { double x; int y; }; XY xy = {}; char* ptr = reinterpret_cast<char*>(&xy) + sizeof(double); (*reinterpret_cast<int*>(ptr))++; or even (placement new): unsigned char* buf = new unsigned char[12]; buf += 4; new (buf) int(0); // Create an int object in the buffer. (*reinterpret_cast<int*>(buf))++; delete[] buf; But in each case an int object has had its lifetime begin before you can treat the bytes in memory like an int. Everything else is UB.
- bonzini 7y agoYou cannot do the last unless you know that the argument of placement new is suitably aligned to receive an int object, however.