I've heard that Python has automated garbage collection, but C ++ doesn't. What does it mean?
This means that the python user does not need to clean up their dynamically created objects, for example, you are required to do this in C / C ++.
Example in C ++:
char *ch = new char[100];
ch[0]='a';
ch[1]='b';
//....
// somewhere else in your program you need to release the alocated memory.
delete [] ch;
// use *delete ch;* if you've initialized *ch with new char;
in python:
def fun():
a=[1, 2] #dynamic allocation
a.append(3)
return a[0]
python takes care of "a" by itself.
source to share
From Wikipedia http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29 :
...
Garbage collection frees the programmer from manually managing memory allocation and freeing memory. As a result, certain categories of errors are eliminated or significantly reduced:
-
Spoofing pointer errors that occur when a piece of memory is freed while there are still pointers to it and one of those pointers is being used.
-
Double free errors that occur when a program tries to free an area of ββmemory that is already free.
-
Some types of memory leaks into which a program cannot load memory for free, which is no longer referenced by
any variable, leading, over time, to memory depletion.
...
The basic principles of garbage collection are:
- Search for data objects in a program that cannot be accessed in the future
- Recover resources used by these objects
source to share
Others have already answered the main question, but I would like to add that garbage collection is possible in C ++. It's not as automatic as Python, but it's doable.
Smart pointers is probably the simplest form of garbage collection C ++ - std::auto_ptr
, boost::scoped_ptr
, boost::scoped_array
which frees up memory after its destruction. Here's an example in one of the previous answers, which could be rewritten as:
boost::scoped_array<char> ch(new char[100]);
ch[0] = 'a';
ch[1] = 'b';
// ...
// boost::scoped_array will be destroyed when out of scope, or during unwind
// (i.e. when exception is thrown), releasing the array memory
There are also boost::shared_ptr
, boost::shared_array
which implement reference counting (like Python). And there are full blown garbage collectors designed to replace standard memory allocators, for example. Boehm gc .
source to share
This basically means that they are handling memory resources. When you need memory, you usually request it from the OS and then return it back.
With python, you don't need to worry about returning it, and in C ++, you need to keep track of what you asked for and return it back, easier, another executor, you choose your tool.
source to share