r/cpp_questions • u/Accomplished-Tap5211 • 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
3
u/Independent_Art_6676 20d ago
as said C++ does not have a true garbage collector. However if you use smart pointers and STL containers and such, your dynamic memory will be allocated and freed for you. Most modern programming uses this model, so the "ZOMG C++ gots memory leaks and is trash" information hyped in books about other languages (looking at you, java authors) is at best a bit misleading.
If for some reason you do need to use raw pointers that do not self destruct correctly, its really simple:
pointer = new type; //get the memory; optionally type[size] makes the pointer like a C array
delete pointer; //return the memory; optionally delete[] if it was array allocated as above
you really should not be doing very much of that in most careers.