Page 1 of 1

how can i implement operator new or delete?

Posted: Thu Dec 04, 2003 8:54 am
by xiaohan
i know i should write it like this:

void *operator new(size_t size)
{
return malloc(size);
}

but there is a question.
as we know, the operator new() would call constructor of the object.
in the code, i don't call the constructor,
so, i want to know,how can i do it ?
the same as delete() which should call deconstructor.

i need your help!
thank you very much!

Re:how can i implement operator new or delete?

Posted: Thu Dec 04, 2003 9:49 am
by Tim
No. The compiler inserts the call to the constructor after the call to new. The same applies to delete.

Re:how can i implement operator new or delete?

Posted: Thu Dec 04, 2003 10:38 am
by Solar
In other words, what you are implementing is the operator new, which is solely responsible for allocating memory. The constructor is called by the keyword new, implemented by the compiler.

(I know, that's not 100% correct in the eyes of a language lawyer, but it makes the thing understandable.)

Re:how can i implement operator new or delete?

Posted: Thu Dec 04, 2003 9:42 pm
by Schol-R-LEA
To put it another way, the new which you actually invoke is a built-in meta-operator which can call a user-supplied new as part of it's operation.