0

I am trying to run the constructor/default initializer of a class on a specific memory location.

I am trying to use pooling so I have allocated memory (with malloc) for the object and I have the address of where I would like to go.

I just don’t know how to run the constructor of the object on that void* location.

Is this possible?

J.Doe
  • 1,502
  • 13
  • 47

1 Answers1

3

Read a lot more about C++ (it is a very complex programming language; few people master it entirely, and I certainly don't). I recommend a good book such as Programming: Principle and Practice Using C++ (by the main designer of C++, Stroustrup). Then see some C++ reference site and some standard like n3337 (for C++11) or some newer version (like C++14 or C++17).

You want the placement new, so to construct an object of class Cla with argument 1 at location of pointer p (declared void*p;) you code:

Cla*ptr = new(p) Cla(1);

BTW, if SubCla is a subclass of Cla (having an appropriate constructor of two arguments) you can of course have Cla*ptr = new(p) SubCla(1, "x");

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547