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.
You can use the "placement new" operator for this:
Foo *buf = malloc( sizeof(Foo) );
Foo *p = new (buf) Foo();
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With