|
-
May 10th, 2003, 05:20 AM
#1
Placement new with HeapAlloc
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
PHP Code:
// 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.
Last edited by usman999_1; May 10th, 2003 at 05:24 AM.
-
May 11th, 2003, 04:46 AM
#2
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
Code:
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
Code:
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
-
May 11th, 2003, 11:47 AM
#3
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|