I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?
views:
334answers:
7I heard that Python has automated "garbage collection" , but C++ does not. What does that mean?
That means that python user doesn't need to clean his dynamic created objects, like you're obligated to do it 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 about "a" object by itself.
It basically means the way they handle memory resources. When you need memory you usually ask for it to the OS and then return it back.
With python you don't need to worry about returning it, with C++ you need to track what you asked and return it back, one is easier, the other performant, you choose your tool.
From Wikipedia http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29:
...
Garbage collection frees the programmer from manually dealing with memory allocation and deallocation. As a result, certain categories of bugs are eliminated or substantially reduced:
Dangling pointer bugs, which occur when a piece of memory is freed while there are still pointers to it, and one of those pointers is used.
Double free bugs, which occur when the program attempts to free a
region of memory that is already
free.Certain kinds of memory leaks, in which a program fails to free
memory that is no longer referenced
by any variable, leading, over time, to memory exhaustion.
...
The basic principles of garbage collection are:
- Find data objects in a program that cannot be accessed in the future
- Reclaim the resources used by those objects
It means you don't allocate and deallocate memory, but that the language does it for you.
Others already answered the main question, but I'd like to add that garbage collection is possible in C++. It's not that automatic like Python's, but it's doable.
Smart pointers are probably the simplest form of C++ garbage collecting - std::auto_ptr
, boost::scoped_ptr
, boost::scoped_array
that release memory after being destroyed. There's an example in one of the earlier answers, that 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's memory
There are also boost::shared_ptr
, boost::shared_array
that implement reference counting (like Python). And there are full-blown garbage collectors that are meant to replace standard memory allocators, e.g. Boehm gc.
As you have got your answer, now it's better to know the cons of automated garbage collection: it requires large amounts of extra memory and not suitable for hard real-time deadline applications.