Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit constructor call

Tags:

c++

I'm wondering if there is some sort of trick to explicitly call a constructor using object pointer. If that was a legal syntax it would look like this:

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

p->Foo::Foo();

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

like image 320
JMH Avatar asked May 26 '11 17:05

JMH


4 Answers

You can use the "placement new" operator for this:

Foo *buf = malloc( sizeof(Foo) );
Foo *p = new (buf) Foo();
like image 184
Dr. Snoopy Avatar answered Nov 19 '22 10:11

Dr. Snoopy


Use placement new:

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

(ommitting any out-of-memory checks here)

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

like image 43
Alexander Gessler Avatar answered Nov 19 '22 11:11

Alexander Gessler


You can construct new object at some address using placement new.

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

You can read more at wikipedia's article about it

like image 34
Nekuromento Avatar answered Nov 19 '22 09:11

Nekuromento


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

If you want all objects of a class to be in memory allocated with malloc, you can overload operator new (and operator delete) for that class, and have them call malloc to get the raw memory. This relieves client code of the extra steps of separate allocation/initialization.

If you want all objects in a collection (or more than one collection) to be in memory allocated with malloc, you can supply an allocator to the collection to make that happen. Again, this relieves client code of dealing with the allocation, and lets the container look, act, and "feel" like a normal container.

like image 25
Jerry Coffin Avatar answered Nov 19 '22 11:11

Jerry Coffin