tags:

views:

198

answers:

6

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.

+15  A: 

Er...use new? That's kind of the point. You can also call the constructor explicitly, but there's little reason to do it that way

Using new/delete normally:

A* a = new A();

delete a;

Calling the constructor/destructor explicitly ("placement new"):

A* a = (A*)malloc(sizeof(A));
new (a) A();

a->~A();
free(a);
Michael Mrozek
You should also mention that you need to call the destructor explicitly when using placement new, and not use 'delete' to destroy it.
Rudi
@Rudi Added, thanks
Michael Mrozek
+8  A: 

You can use "placement new" syntax to do that if you really, really need to:

MyClassName* foo = new(pointer) MyClassName();

where pointer is a pointer to an allocated memory location large enough to hold an instance of your object.

warrenm
You don't have to save the return as `foo == pointer`
R Samuel Klatchko
`foo` and `pointer` may be of different types, or `pointer` may be an expression that calculates an offset into a larger block of memory.
warrenm
@RSamuel: I usually do it that way in the rare occasion I need placement new. I make sure I treat `pointer` as just memory and get an object through `new`. It also "hides" the cast.
GMan
+2  A: 

Take a look at placement new operator, which constructs an object on a pre-allocated buffer.

Alex Farber
+4  A: 

Prefer new.

But if for some reason you have raw memory, you can construct it with "placement new":

new (ptr) TYPE(args);

And since you won't be using delete, you'll need to call the destructor directly:

ptr->~TYPE();
R Samuel Klatchko
+4  A: 

Use placement new. The advice is handy:

ADVICE: Don't use this "placement new" syntax unless you have to. Use it only when you really care that an object is placed at a particular location in memory. For example, when your hardware has a memory-mapped I/O timer device, and you want to place a Clock object at that memory location.

Igor Zevaka
+3  A: 

You mis-understand what malloc does. malloc does not create objects, it allocates memory. As it does not create objects there is no object for it to call a constructor to create.

If you need to dynamically create an object in C++ you need to use some form of new.

Charles Bailey