Archived

This topic is now archived and is closed to further replies.

Dreamforger

delete[] or delete

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites