Re:NanoLog – a nanosecond scale logging system for C++
by MauranKilom on Sunday September 01, 2019 @03:16PM
(#20854144)
That'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.
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.
You can do
or (given knowledge about compiler padding): or even (placement new): 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.