简体   繁体   中英

Cast first 16 bytes of allocated memory into a UDT

class Object{
  // some code here
}

char* c = new char[64];

From what I understand from the code sample above, I have allocated 64 bytes of memory in the heap. So now I have a block of memory to work with.

My question: is it possible to cast just the first 16 bytes into an Object* of the above allocated 64 bytes? If yes, how do I do it? If no, why?

You cannot 'cast' the memory to type Object . It would violate strict aliasing rule at the bare minimum, and potentially (depending of Object ) violate it start of lifetime as well, and lead to undefined behavior.

Instead, you want to use placement new to properly construct the object in the allocated space. The code will look like this:

class Object{
  // some code here
}

char* c = new char[64];
static_assert(sizeof(Object) <= 64, "Can't use allocated storage");
Object* p = new (c) Object(/* args */);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM