Re: operator new (iNumBytes) vs std::malloc(iNumBytes)
On May 10, 10:36 pm, "Thomas J. Gritzan"
<phygon_antis...@gmx.de> wrote:
James Kanze schrieb:
On May 10, 2:12 pm, Andrew Tomazos <and...@tomazos.com> wrote:
Given:
void f(void* p) { ... }
and assuming the operator new has not been overloaded, what
are the concrete differences in behaviour of:
void* p = operator new(iNumBytes);
f(p);
vs
void* p = std:malloc(iNumBytes);
f(p);
That are visible by f?
The main one is that in the first, p must be freed by
::operator delete, and in the second, by std::free.
I think that it's also important to know that, in the second,
p can be NULL.
Very good point (and I'm surprised I forgot it). The two differ
considerably in the way they report an error: ::operator new
raises an exception (std::bad_alloc, or something which derives
from std::bad_alloc), std::malloc returns a null pointer (which
you have to test for).
Another difference, at least in theory, is that you can replace
::operator new, but not std::malloc. I say in theory, because
in all implementations I actually know, you can also replace
std::malloc. The standard says that attempting to do so is
undefined behavior, but in practice, it always works. On the
other hand, you almost certainly have to use implementation
dependent code if you replace std::malloc, where as if you
replace ::operator new, you can portably use std::malloc for the
actual allocation.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34