Click to See Complete Forum and Search --> : new operator and clean up
Galen
November 14th, 2005, 01:06 PM
I noticed in some code that a new object is being created on a pointer that already points to an object. However, I haven't seen any problems resulting from this -- no error or exceptions. Is the old object being garbage collected? Here is the offending line, which is being called multiple times:
m_db = new my_database( dbName );
What is the proper way to reuse a pointer in managed code?
Thank you,
Galen
NoHero
November 14th, 2005, 03:39 PM
If there are no references left pointing at this object, the object is free for being garbage collected. AFAIK the garbage collector may run anytime and you can also run the garbage collector manually.
cilu
November 15th, 2005, 07:34 AM
I noticed in some code that a new object is being created on a pointer that already points to an object. However, I haven't seen any problems resulting from this -- no error or exceptions. Is the old object being garbage collected?
That is the whole point of the garbage collector: collecting unreferenced objects and freeing the memory they hold. In a managed environment you don't need to release memory manually. the GC is talking care of it. However, the actions of the garbage collector is non-deterministic, i.e. you don't know when the GC decides to run a new collection and free the memory. If you need to manually dispose resources at a certain moment, call the Dispose method.
Implementing Finalize and Dispose to Clean Up Unmanaged Resources (http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconFinalizeDispose.asp)
Implementing a Dispose Method (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconImplementingDisposeMethod.asp)
Cleaning Up Unmanaged Resources (http://msdn.microsoft.com/library/en-us/cpguide/html/cpconCleaningUpUnmanagedResources.asp)
codeguru.com
Copyright WebMediaBrands Inc., All Rights Reserved.