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.
This is called placement new, which constructs an object on a pre-allocated buffer (you specify the address).
Edit: more useful link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With