Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc and constructors

Tags:

c++

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.

like image 637
ckv Avatar asked Jun 08 '10 06:06

ckv


People also ask

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.

What is difference between new () and malloc ()?

malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific for C++ only. Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call the constructor of a class whereas “malloc()” does not.

What exactly is malloc?

In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.

What is malloc () in C++?

The malloc() function in C++ allocates a block of uninitialized memory to a pointer. It is defined in the cstdlib header file.


2 Answers

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); 
like image 177
Michael Mrozek Avatar answered Oct 04 '22 05:10

Michael Mrozek


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.

like image 39
warrenm Avatar answered Oct 04 '22 05:10

warrenm