new and delete implementation

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
User avatar
AlfaOmega08
Member
Member
Posts: 226
Joined: Wed Nov 07, 2007 12:15 pm
Location: Italy

new and delete implementation

Post by AlfaOmega08 »

I've already implemented a malloc and free functions. Since I'm creating a C++ kernel, now I need to implement new and delete too...
Initially I thinked that

Code: Select all

void *operator new(size_t size) {
        return malloc(size);
}
Is the only think I need. But I read that new and delete also call constructors and deconstructors. How can I call the contructor of the new class?
I also read that the return type of new isn't void * but a pointer to the type of the parameter.
Eg

Code: Select all

new(sizeof(short int)) returns short int *
new(Class1()) returns Class1 *
How is this done in C++?

Thanks
Please, correct my English...
Motherboard: ASUS Rampage II Extreme
CPU: Core i7 950 @ 3.06 GHz OC at 3.6 GHz
RAM: 4 GB 1600 MHz DDR3
Video: nVidia GeForce 210 GTS... it sucks...
xyzzy
Member
Member
Posts: 391
Joined: Wed Jul 25, 2007 8:45 am
Libera.chat IRC: aejsmith
Location: London, UK
Contact:

Re: new and delete implementation

Post by xyzzy »

Use of operator new and delete automatically calls the constructors and destructors, you don't need to do that in your implementation.

And yes, the return type automatically gets converted to a pointer to the type being allocated. Also, your usage of new in that example is wrong - new takes a type as a parameter, not a size. It should be:

Code: Select all

new short int;
If you want to pass arguments to constructors when allocating a class, use:

Code: Select all

new MyClass(foo, bar);
Post Reply