If I'm writing 100% ANSI C but compiling in .cpp files will the compiler automatically "optimize" malloc and free calls to new and delete? Does that even make sense given their differences? I didn't think this is how it worked but a friend of mine said this is what happens.
C++ is very specific in c.malloc
:
The functions
calloc()
,malloc()
, andrealloc()
do not attempt to allocate storage by calling::operator new()
.The function
free()
does not attempt to deallocate storage by calling::operator delete()
.
There's a bit of an ambiguity in the question.
int *ip1 = malloc(sizeof int);
int *ip2 = new int;
Those two in fact do the same thing: create an uninitialized value on the heap and assign its address to the pointer on the left-hand side.
But:
struct S { /* whatever */ };
S *sp1 = malloc(sizeof S);
S *sp2 = new S;
Those two don't necessarily do the same thing. If S
has a constructor, new S
will allocate memory and call the constructor ; malloc(sizeof S)
will only allocate memory.
I mentioned an ambiguity. There's another possible meaning for "replace new
, and that is using calls to operator new
:
struct S { /* whatever */ };
S *sp1 = malloc(sizeof S);
S *sp2 = ::operator new(sizeof S);
On the surface, by default these two do the same thing: they allocate memory on the heap for an object of type S
and return a pointer to that memory; neither one initializes the object. But there's an important difference. If malloc
can't allocate memory it returns a null pointer. If operator new
can't allocate memory it throws an exception of type std::bad_alloc
(there's more to it than that, but that's enough difference for now).
That's also true for new S
: it throws an exception if it can't allocate memory, while malloc
returns a null pointer.
Do C++ compilers generally “optimize” malloc and free to new and delete?
No .
Optimizing is an act that reduces the workload of your program.
Since new
and delete
invoke constructors and destructors respectively, while malloc()
and free()
do not , it makes no sense to optimize them.
Usually new
will call malloc()
, which also adds to my point above, as mentioned in Does ::operator new(size_t) use malloc()?
PS: "I'm writing 100% ANSI C" is not going to make a C++ compiler happy in any way...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.