initialize a class object in the malloc address?

c++

Solution

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.

Problem

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?

Original source

Related problems