how can i implement operator new or delete?

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
xiaohan

how can i implement operator new or delete?

Post 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!
Tim

Re:how can i implement operator new or delete?

Post by Tim »

No. The compiler inserts the call to the constructor after the call to new. The same applies to delete.
User avatar
Solar
Member
Member
Posts: 7632
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:how can i implement operator new or delete?

Post 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.)
Every good solution is obvious once you've found it.
Schol-R-LEA

Re:how can i implement operator new or delete?

Post 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.
Post Reply