Click to See Complete Forum and Search --> : Placement new with HeapAlloc


usman999_1
May 10th, 2003, 05:20 AM
Hi*!
I have a Dll that dll implements a class. I have a class factory kindof function in the DLL that gives me an Object of the class in DLL. I dont want to include any libs in my project for the DLL. The class factory in the Dll does something like

// Doing some other stuff too
void* pMem = HeapAlloc(GetProcessHeap(), 0, sizeof(CMyDllClass));
return new (pMem) CMyDllClass();

Is it correct??? It works but i want to know if theres a more appropriate way to achieve the same????
Secondly when i dont need the object, what should i do???? delete will also i think delete the memory & If i use Heap functions to delete the memory, then do i have to call the dtor myself?????
Thanks for ur time,
Regards,
Usman.

rxbagain
May 11th, 2003, 04:46 AM
I think, your object has it's own operator new that will return the memory you allocated using HeapAlloc. If I'm not wrong, it looks something like this

void *CMyDllClass::operator new (size_t n, void *pv)
{
...
...
return pv;
}

If this is the case, the code you showed will still be correct, because it will just return to you the memory allocated by the HeapAlloc function. If in the operator new, it again allocated memory, then I think you have to refine the code.

With regard to the deallocation of the object. I think, if I'm not wrong again, that your object has it's deallocator that calls HeapFree. It might look something like this

void CMyDllClass::operator delete (void *pv) {
...
HeapFree(GetProcessHeap(), 0, pv);
...
}

If this is the case, you can simply call the delete myobj to release the memory. If there is no such function in your object, It's better for you to delete the object using HeapFree.

Hope this will clarify your concern

emmenjay
May 11th, 2003, 11:47 AM
Hi usman999_1

I think that rxbagain has misunderstood what you are doing. That said, an overloaded new operator might be just the ticket.

If you overload new for CMyDllClass to use HeapAlloc(), then overload delete to use HeapFree(), that will be much safer.

By using placement new, you cannot really call delete so you will have to call HeapFree(), which means the destructor is never called.

I think Scott Meyers' "Effective C++" has a good section on overloading new and delete (from my bad memory). Check that out before going too far.