views:

236

answers:

7

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.

A: 

Search Google for "placement new".

florin
+12  A: 

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

Edit: more useful link

Samuel_xL
+2  A: 

This is placement-new. This tell new to return a specific address instead of actually allocating memory. But importantly, it is still invoking the constructor.

This technique is needed when you need to create an object at a specific memory address.

R Samuel Klatchko
+4  A: 

That is the placement new. It will run any constructors and initialization needed, but you are supplying the memory instead of having new allocate it for you.

Details have already been provided on this site.

Shmoopty
+1  A: 

That construct is placement new. Rather than allocating memory and invoking the class constructor the compiler constructs the instance in the memory location specified. This sort of control over memory allocation and deallocation is tremendously useful in optimizing long running programs.

William Bell
+2  A: 

Scott Meyers describes this technique very well in Effective C++.

DanDan
A: 

If you put a file read after the malloc but before the new, you'd be doing the common (but ugly) Load-In-Place hack for creating pre-initialized C++ objects in a serialized buffer.

Adisak