BekTek said:
I'm still confused about the differences between malloc and operator new..
I know that when we work with class object and use operator new/delete, the
ctor and dtor
get called as expected, but malloc and free do not..
There is a difference between operator new and the new operator: the
latter calls the former.
The new operator is something you will never see. Basically, it does
two things :
1. calls operator new to get some raw memory
2. calls the object's constructor on that memory
As you can see, fiddling with the new operator would require you to call
constructors by hand, which is impossible.
The first point was a call to operator new. That operator you can
overload as any other operator. Its function is to provide a pointer to
enough memory for the object to construct itself; this is a malloc-like
function and actually, the default implementation is usually written in
terms of malloc().
But Herbal Sutter
mentioned in his greate book 'exceptional c++' about free
storage
and heap..
He said they are differenct and we need to know the differences..
That was a theoritical question.
But I'm still confused about they are different..
I've thought actually both new and malloc use heap..
The standard doesn't require them to do so, but that's what happens in
real life.
Calling malloc() returns a pointer to a block of memory on the heap
which has the given size :
malloc(sizeof(MyClass));
returns a pointer to a block of sizeof(MyClass) bytes. That's raw memory.
new MyClass;
return a pointer to a block of sizeof(MyClass) bytes on which the
constructor was called. So that block is not raw memory: it's a valid
object. That was done in two steps, the steps described above.
The conclusion is : malloc() only allocates raw memory and new allocates
raw memory on which the constructor is called. Something like
// what the new operator does behind your back:
// allocate raw memory
MyClass *p = reinterpret_cast<MyClass*>(malloc(sizeof(MyClass)));
// call constructor
p->MyClass();
Of course that code is invalid since calling constructors is illegal,
but that's what the compiler is doing behind your back. Since we're in
C++, the malloc() call is replaced by a call to operator new :
// allocate raw memory
MyClass *p = reinterpret_cast<MyClass*>(operator new(sizeof(MyClass)));
// call constructor
p->MyClass();
And usually, as I said, operator new is implemented in terms of malloc :
void *operator new(std::size_t size)
{
return malloc(size);
}
though you could override it to call some application-specific functions
(such as memory pool functions).
Jonathan