Page 1 of 1

new and delete implementation

Posted: Sun Sep 14, 2008 3:42 am
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

Re: new and delete implementation

Posted: Sun Sep 14, 2008 4:28 am
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);