Skip to main content
gamedev.net
🔒 Locked

delete[] or delete

Started by Dreamforger Aug 11, 2002 at 6:54 AM 3 replies 450+ views
Original Post
Dreamforger
Dreamforger
I know: delete[] for arrays, delete for single instances. Now it gets tricky: I have a factory function that creates memory, with content for other functions. It is then the obligation of the caller of the factory to delete the memory when no longer needed. The factory allocates the memory as
BYTE* ret = new BYTE[ count ]   
where count is a variable passed into the function. Then the memory is returned via a LPVOID return. The caller then casts the return to the desired type
    
LPVOID factory(DWORD count)
{
    BYTE* ret = new BYTE[ count ];
    // fill ret with data, i.e parts of files


    return (LPVOID)ret;
}

void a_user()
{
    DWORD* data = (DWORD*)factory( sizeof(*data) );

    // now data is interpreted as DWORD data 

}    
My question is how do I delete the 'data' variable properly? The factory allocated 4 BYTEs so I'd use delete[] The DWORD* gets deleted in steps of 4 bytes anyway (or isn't it?), so I'd use delete But which is correct? Thanks P.S I know there are other ways to do this, but I like it that way. So if you just want to tell me that this is bad programming you better give a good reason [EDIT: block comment to line comment] --------------------------- I may be getting older, but I refuse to grow up [edited by - Dreamforger on August 11, 2002 8:20:58 AM]
I may be getting older, but I refuse to grow up
Dreamforger
Dreamforger
Thank you for the reply.

I''m going to die for asking this, but I just have to
quote:
Original post by LordLethis
... delete the array using delete [count] data.


I have never seen, and never used, delete[ ] with a variable/value in the brackets. Have I never done it right? should there always be a count in the brackets?

And Inlining the function is not an option as ''fill with data'' takes long enough in general. I''ll keep it in mind though



---------------------------
I may be getting older, but I refuse to grow up
I may be getting older, but I refuse to grow up
Ersvik
Ersvik
In early implementations of c++ you could and should use a number inside the brackets. In modern versions, however, any number placed inside brackets will be ignored.

About the array, when the new operator store the length of the array for delete to use later, I think there would be no reason to it in any other format than byte count. So I''d guess it''s just fine to do what you do.

Johan
SabreMan
SabreMan
quote:
Original post by Dreamforger
It is then the obligation of the caller of the factory to delete the memory when no longer needed.

Learn about smart pointers. By returning a suitable smart pointer (in this case, std::auto_ptr), you can remove this obligation.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.