4

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.

Mike
  • 41
  • 3

7 Answers7

11

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

Edit: more useful link

KeatsPeeks
  • 19,126
  • 5
  • 52
  • 83
5

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.

Community
  • 1
  • 1
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
2

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
  • 74,869
  • 16
  • 134
  • 187
2

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

DanDan
  • 10,462
  • 8
  • 53
  • 69
1

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
  • 543
  • 2
  • 4
0

Search Google for "placement new".

florin
  • 13,986
  • 6
  • 46
  • 47
0

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.

Community
  • 1
  • 1
Adisak
  • 6,708
  • 38
  • 46