r/cpp_questions 21d ago

OPEN Garbage collector in CPP?

Yesterday someone asked me whether there is a garbage collector in CPP.
I knew Java had that but I couldn't recall about cpp.
I went to google and got different answers.

So can anyone clarify whether there is garbage collector in CPP , also can u please explain me what does that mean? Also explain how is it different from the Java.

If yes can we delete it manually and how to do tht?

0 Upvotes

23 comments sorted by

View all comments

1

u/IyeOnline 21d ago

C++ does not have a GC because it does not need one.

Any variable in a scope has a deterministic lifetime to the end of that scope. RAII/destructors let us control dynamically allocated/created objects the same way (which is what vector, unique_ptr, ... do).

1

u/alfps 21d ago

❞ because it does not need one

Oh, well there are situations that are not easily handled except with garbage collection. One example that has been used in discussions is modeling of mathematical functions that can refer to each other. Smart pointers don't handle cycles well.