Question:
what is a garbage collection in C++?
Ern Privado
2011-03-17 07:55:07 UTC
like if i have a program that get a random lock combinations then these combinations will be transfer in a file.. then I will just use one combination.. I can't really understand the question.. it just said that Do Garbage Collection.
Three answers:
cosimo
2011-03-17 07:59:11 UTC
Garbage collection is where you dispose of any objects you've created dynamically, i.e. on the heap.



If you use the "new" operator to create an object then grabage collection means using "delete" (or delete[] if you created an array) on the object once you've finished with it.



Java does this for you, which is one of the reasons it has issues with hard real-time systems.
koppe74
2011-03-17 15:18:10 UTC
Garbage collection means that you clean-up objects and variables when they're no-longer in use. Some languages does this automatically, C++ does not.



What boils down to, is that if you have dynamically allocated memory (i.e the new keyword) for something (e.g. a dynamic array), be sure you un-allocate it (i.e. the delete keyword) when it's no longer needed!



For a class you would typically write a *constructor* to allocate any needed memory for an object... if you've done that, be sure you also write a *de*structor to un-allocate the memory when the object goes out of scope. (Of course a class may use normal variables and fixed arrays; these are automatically destroyed when they go out of scope.)



If you don't free-up dynamically allocated memory when it's no longer needed, your program may sooner or later use-up all the memory it has available, and crash.
?
2011-03-17 15:01:55 UTC
Garbage collection in C++ is the method used for clearing memory (RAM typically). The "garbage collector" passes once in awhile(depends on a lot of factors) and checks if variables are irrelevant (function specific, etc...) and if they are, they clear them from memory. The perfectly developed program would never need any of that since you would delete,undim...whatever you call it all vars that are not to be used anymore. But in modular programming, sometimes you don't have access to everything. Most ECMA compliant scripting systems use the "garbage collector" method to keep memory usage from building up.



Good luck!


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...