using malloc inside overloaded new operator

V

Vinu

Hi,

I am maintaining a C++ project which is a server which continuously
receives requeste from clients.

I have noticed that we overload the new operator and in it then call
malloc to allocate memory.

Specifically the code is something like this.

template <class T>
class CSimpleList
{
public:
CSimpleList()
{
// some code
}
inline void* operator new(size_t tSize){ return malloc(tSize); }
inline void operator delete( void* p ){ free(p); }
};

Is it all right to use it like this. Because i was under the impression
that even after you overload the new operator, it does memory
allocation implicitly(i.e even if you dont do a malloc or some other
kind of memory allocation).
So in the above case, wont memory be allocated twice.

Thanks
Vinu
 
B

benben

Is it all right to use it like this. Because i was under the impression
that even after you overload the new operator, it does memory
allocation implicitly(i.e even if you dont do a malloc or some other
kind of memory allocation).
So in the above case, wont memory be allocated twice.

No, it won't. Operator new does allocation by calling function operator
new(), nothing more, end of story. In fact, in many systems the default
operator new() function does nothing more than just a malloc call.

ben
 
B

benben

Will the constructor be called if I use a malloc() inside the
overloaded new ?

Yes.

T* i = new T;

is equivalent to:

T* i = (T*) malloc(sizeof(T));
i->T::T(); // pseudo C++ code

ben
 
J

Jonathan Mcdougall

Yes.

T* i = new T;

is equivalent to:

T* i = (T*) malloc(sizeof(T));
i->T::T(); // pseudo C++ code

No, it is equivalent to

T* i = (T*)operator new(sizeof(T));
i->T::T(); // pseudo C++ code

To the OP: What you overload is the operator new call (forwards to
malloc() most of the times, but may do anything you want, including
printing "hello world" and returning 123), nothing else. The 'new
operator' (as opposed to the operator new) cannot be overloaded.

Jonathan
 
V

Vinu

So Whats the difference between "operator new" and "new operator".

what i understand is "operator new" is just like "operator ==" or any
of the other operators.

So then whats "new operator"

Thanks
Vinu
 
J

Jonathan Mcdougall

Don't top-post. Rearragned.
So Whats the difference between "operator new" and "new operator".

what i understand is "operator new" is just like "operator ==" or any
of the other operators.

So then whats "new operator"

See my post in http://tinyurl.com/by9l2.


Jonathan
 

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
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top