What is garbage collection in java? Why C++ doesn't have garbage collection? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What is garbage collection in java? Why C++ doesn't have garbage collection?

20th Jul 2017, 11:37 AM
Viraj Singh
Viraj Singh - avatar
3 Answers
+ 1
It is impossible to add general garbage collection in a way that languages like Java/C# have it (at least without enforcing some restrictions.) For example in C++ it is completely valid to have a pointer in the middle of a data structure due to pointer arithmetic. For example, you could take a pointer to User and move it 1 byte forward. The pointer would still point at some data in User, but now the reference count has gone down, since you no longer have a pointer to the whole User record, hence the GC could be inclined to delete the User. Now  you might be thinking, the GC could monitor these changes and act accordingly. Why yes of course, but that would mean that all pointer arithmetic would have to be monitored by the GC, introducing a lot of overhead. There are also cases where you could somehow get a pointer to some object indirectly, and the GC would have no way of knowing that. This doesn't happen in languages like C#/Java, since you can only have a reference to the whole object (in C# you can get around this with unsafe pointers, but it has other restrictions.) All in all, you can't easily implement a GC while keeping pointer arithmetic.
23rd Dec 2017, 6:13 PM
Bits!
+ 2
C++ has a similar concept to garbage collection. They are called smart pointers. Ex, unique_ptr, shared_ptr, and weak_ptr
20th Jul 2017, 1:16 PM
aklex
aklex - avatar
+ 1
It is how Java clears memory. when it decides things are no longer necessary it "collects the garbage" .. This is one of the things people like c++ over Java for. In C++ You handle that yourself. Gives you more control
20th Jul 2017, 12:11 PM
LordHill
LordHill - avatar