Jump to content
  • Advertisement

Archived

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

KurtCPP

About local pointers and new allocations.

This topic is 5660 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi everyone!! Does someone here ( don''t say ''no'', I already know you''d be lying) whether a local pointer allocated using the new operator within the function where it''s been declarated will automatically be deleted when the program exits from this function?? Actually, I''m nearly certain it won''t so that my question should rather be the following : ''Is it necessary to dynamically allocate only global variables in order to always be able to properly deallocate them later?'' Thank you all in advance for your help!! Prog, Sex & Rock''n''Roll : I don''t like the Prog but the prog likes me.

Share this post


Link to post
Share on other sites
Advertisement
Anything that is allocated using the new operator is NEVER automatically deleted.

It must ALWAYS be explicitly freed with an appropriate call to delete.

Share this post


Link to post
Share on other sites
GOT IT, GENERAL !!
Thank you, brother, I won''t forget that.

Prog, Sex & Rock''n''Roll :
I don''t like the Prog but the prog likes me.

Share this post


Link to post
Share on other sites
Your second question got unanswered.

You should try to avoid global variables, they can be avoided in most cases if you design the program properly. So, if you allocate some memory inside a function, you should delete it before the function exits. And if you have class members allocated dynamically, you usually delete the memory in the destructor.

And in most cases where a function needs to manipulate some memory, that an outside function needs, the pointer should be passed as an argument and the memory allocated and deleted in the outside function. There are rare cases where allocating memory inside a function and returning it makes sense, but then the function has to be documented properly so that the caller knows he is responsible for deleting the memory. Another possibility in a case like that, is to use some kind of smart pointer, that automatically deletes the memory, when the pointer goes out of scope.

So, in other words, there aren''t any cases where you need a global variable to keep track of the memory and make sure you are able to delete it afterwards.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!