Explicit constructor call

I am wondering if there is any trick to explicitly invoke the constructor using an object pointer. If it was legal syntax, it would look like this:

Foo *p = malloc( sizeof(Foo) ); p->Foo::Foo(); 

PS I know that I can do Foo *p = new Foo(); , but there is a serious reason for using malloc () explicitly.

+7
source share
5 answers

To do this, you can use the "Place New" operator:

 Foo *buf = malloc( sizeof(Foo) ); Foo *p = new (buf) Foo(); 
+16
source

Use posting new :

 Foo* p = new(malloc(sizeof(Foo))) Foo; 

(any checks out of memory are skipped here)

Basically, new(address) Foo() builds an object of type Foo at the location pointed to by address , in other words: it calls the constructor.

+9
source

You can create a new object at any address using the new placement.

 void *buf = malloc(sizeof(Foo)); Foo *p = new (buf) Foo(); 

Read more about the wikipedia article about him at

+3
source

Others have already indicated that you can use the new placement. This works well if you want certain, specific class objects to be in memory allocated with malloc . As also pointed out, when you do this, you need to explicitly call dtor.

If you want all the objects in the class to be in memory allocated with malloc , you can overload operator new (and operator delete ) for this class and ask them to call malloc to get raw memory. This frees up client code for additional separate allocation / initialization steps.

If you want all objects in a collection (or more than one collection) to be in memory allocated with malloc , you can provide a allocator for the collection to make this happen. Again, this saves the client code from working with distribution and allows the container to look, act and "feel" like a regular container.

+3
source
  struct MyClass { MyClass() { std::cout << "ctor" << std::endl; } ~MyClass() { std::cout << "dtor" << std::endl; } }; int main(int argc, char *argv[]) { // Allocate memory and call constructor MyClass myObj; // Call constructor again with placement new new (&myObj) MyClass; } 
0
source

All Articles