How can I call a constructor on a memory region that is already allocated?
The this keyword in Java is a reference to the object of the current class. Using it, you can refer a field, method or, constructor of a class. Therefore, if you need to invoke a constructor explicitly you can do so, using "this()".
Unlike new and delete operators malloc does not call the constructor when an object is created. In that case how must we create an object so that the constructor will also be called.
Explicit Constructor Chaining using this() or super() To call a non-args default constructor or an overloaded constructor from within the same class, use the this() keyword. To call a non-default superclass constructor from a subclass, use the super() keyword.
A constructor does not allocate memory for the class object its this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator.
You can use the placement new constructor, which takes an address.
Foo* foo = new (your_memory_address_here) Foo ();
Take a look at a more detailed explanation at the C++ FAQ lite or the MSDN. The only thing you need to make sure that the memory is properly aligned (malloc
is supposed to return memory that is properly aligned for anything, but beware of things like SSE which may need alignment to 16 bytes boundaries or so).
Notice that before invoking placement new
, you need to call the destructor on the memory – at least if the object either has a nontrivial destructor or contains members which have.
For an object pointer obj
of class Foo
the destructor can explicitly be called as follows:
obj->~Foo();
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