2

say we have

Class A{};
int *p = malloc(100);
A a; //default constructor in use
*p = A; (question???)

how to initialize an object of type A on alloc memory p?

bbc
  • 1,061
  • 4
  • 13
  • 21

1 Answers1

8

To instantiate a class instance at a specific address you need to use placement new.

#include <new>
#include <stdlib.h>

class A
{};

int main()
{
  void *p = malloc(100);
  A* a = new(p) A();
  a->~A();  // call destructor explicitly
  free(p);
}

Note that the destructor must be invoked explicitly when using placement new.

Praetorian
  • 106,671
  • 19
  • 240
  • 328