yeah, im a real malloc() person, because i was really into C. i have used localalloc and globalalloc, but its annoying to have to declare a handle and a pointer. but to use new, how would you declare a pointer to an array of chars? like this?
and whats the difference between that and malloc()?
char *chBuffer=new char;
new automatically allocates enough memory for a compound type, (a class for example), with malloc() you would need to calculate the size of the class then allocate the right amount of storage - AND REMEMBER to change that value when you change the class definition, or use sizeof() all over the place!
new also returns a correctly typed pointer, malloc() always returns a void pointer which you need to cast.
With new, you can initialise the object being allocated, not the case with malloc().
new should throw an exception if it fails rather than return a void pointer which then needs to be checked. I say should because although that is the ANSI standard action, I've never used a PC compiler which did that. The C++ compiler on our Alpha servers does.
I think best of all, you can override new and delete.
Both work, one is newer than the other, and is ANSI standard for C++, malloc() is retained in C++ for compatibility reasons.
Use one OR the other, you can get into trouble if you mix them in the same program.
>>> how would you declare a pointer to an array
An array is allocated as...
TypedPointerVar = new VarType [size];
...and deleted like this...
delete  TypedPointerVar;
how do you override those functions? i mean, i know how to override normal functions, but the syntax of new and delete is different from usual.
>>> how do you override those functions?
new and delete are not functions, they are operators, and as such, can be overloaded relative to a class like any other. The skeleton for the overloaded functions are...
... the constructor and destructors are called automatically.
void *operator new (size_t size)
// Do whatever you want, allocate memory and throw a bad_alloc exception if necessary
void operator delete(void *P)
// Do whatever you want, deallocate the memory
*** EDIT ***
This is not Windows specific by the way, that is standard C++.
are the two overrides you quoted there ones that will apply to any new and delete command? and when you say that they can be overloaded relative to a class, how does that work? is it like this?
void *operator myClass::new(size_t size)
void operator myClass::delete(void *ptr)
I have split this stuff from Dark Vipers stuff, as the thread had rapidly developed into two topics.
>>> will apply to any new and delete command?
No. Operator overloading is always relative to a class. If you overload new for class x, then a new x will use the overloaded class member new. new y would use the standard new operator, (assuming of course, new has not been overloaded in class y!).
>>> is it like this?