malloc vs new

P

puzzlecracker

Why is "new" a C++ language-level construct while "malloc" is a
library function?
 
G

Gianni Mariani

puzzlecracker said:
Why is "new" a C++ language-level construct while "malloc" is a
library function?

Firstly, don't compare malloc and new, they are very different.

new ends up calling the "operator new(...)" method to allocate memory
(like what malloc does) followed by a call to the appropriate
constructor. Also new is type-safe, yet malloc is not.

new can also be used to call just the constructor (using the placement
new syntax).

Other than that, it just IS that way.

I suspect you can emulate new using a template, e.g.

int * v = NewFunc< int >( 5 );

So, I think you might be able to do everything new does (except
placement new) with function calls, including array allocations.

I suspect this was a hang-over from simula or somthing.
 
T

Tim Slattery

puzzlecracker said:
Why is "new" a C++ language-level construct while "malloc" is a
library function?

"malloc" goes all the way back to C. All it does is allocate memory
and return a pointer to it. For whatever reason, the designers of the
C language implemented it as a standard library function.

"new" belongs to C++. It's function is to instantiate an object, by
allocating memory and calling the appropriate constructors. Seems
reasonable to me that this function is far more tied to the language
than something that simply allocates storage.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,197
Messages
2,571,041
Members
47,643
Latest member
ashutoshjha_1101

Latest Threads

Top