Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a constructor on an already allocated memory?

How can I call a constructor on a memory region that is already allocated?

like image 579
Ben Avatar asked Feb 06 '09 10:02

Ben


People also ask

How do you call a constructor directly?

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()".

Can malloc call a constructor?

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.

How do you call an explicit constructor?

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.

Does constructor allocate memory?

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.


2 Answers

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).

like image 82
Anteru Avatar answered Oct 07 '22 21:10

Anteru


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(); 
like image 23
Konrad Rudolph Avatar answered Oct 07 '22 22:10

Konrad Rudolph