+ 2
What is garbage collection in java? Why C++ doesn't have garbage collection?
3 ответов
+ 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.
+ 2
C++ has a similar concept to garbage collection. They are called smart pointers. Ex, unique_ptr, shared_ptr, and weak_ptr
+ 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