#include <cstdlib>
#include <cstring>
#include <iostream>
// C++03 only.
int main()
{
std::allocator<unsigned char> alloc;
double d = 8;
unsigned char* buf = alloc.allocate(sizeof(double));
std::memcpy(buf, &d, sizeof(double));
double extract;
std::memcpy(&extract, buf, sizeof(double));
std::cout << extract << '\n';
alloc.deallocate(buf, sizeof(double));
}
I've created storage for an array of bytes that I've never brought to life by initializing it, so its lifetime never started (and in C++03 that is basically impossible to do since the correct way of doing it is by placement new but for arrays it adds a memory offset that you don't know what is it)
But, I don't actually need to "directly read" the data that is in this storage, I do all of this copy-paste of objects by means of std::memcpy
calls.
My doubt is with the second std::memcpy
call. In terms of value access, is it considered that the std::memcpy
is reading the value of each buf
array element so this array must be alive?
NOTE: It has been suggested that, this question is a possible clone of Can memcpy be used for type punning?. That other question is about C, and this question is not about type punning either, although it's related (I wrote originally a wrong question title because I misundertood what type punning actually means). I'm asking here about the precise semantics of the reading-from object that is passed to memcpy
, whether that object must be alive or isn't actually required.