Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct instantiation from void pointer buffer

Here's some C++ code that just looks funny to me, but I know it works.

There is a struct defined, and in the program we allocate memory using a void pointer. Then the struct is created using the allocated buffer.

Here's some code

typedef struct{
 char buffer[1024];
} MyStruct

int main()
{
   MyStruct* mystruct_ptr = 0;

   void* ptr = malloc(sizeof(MyStruct));

   // This is the line that I don't understand
   mystruct_ptr = new (ptr) MyStruct();

   free(ptr);

   return 0;
}

The code has more stuff, but that's the gist of it.

I haven't tested this code, but the code I'm looking at is very well tested, and works. But how?

Thanks.

EDIT: Fixed that memory leak.

like image 274
Mike Avatar asked Nov 29 '22 19:11

Mike


1 Answers

This is called placement new, which constructs an object on a pre-allocated buffer (you specify the address).

Edit: more useful link

like image 91
KeatsPeeks Avatar answered Dec 10 '22 14:12

KeatsPeeks