1

in c++11, we have shared_ptr and when we use it together with the new , we won't have to explicitly call delete later. this part of job has been taken care of by shared_ptr instead.

with that being said, why ppl keep saying there is no garbage collector in c++?

what is missing over here?

can i use / think of shared_ptr as garbage collector in c++?

2 Answers2

1

In languages which have garbage collection, like Java and C#, you cannot avoid it. All objects are automatically garbage collected.

C++ allow you the ability to automatically clean up after yourself, but you have to choose to use it.

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • 1
    follow-up: can i use / think of shared_ptr as garbage collector in c++? –  Aug 01 '14 at 17:47
  • Uh not quite. Garbage collection is an independent process that periodically cleans up unreferenced memory. Smart pointers are just objects that automatically clean up their associated memory when they are destructed. Smart pointers yield essentially no run-time cost, while GC can have the potential of a pretty large run-time cost. – jaredready Aug 01 '14 at 19:57
  • 2
    @ResidentBiscuit Reference counter smart pointers do incur a runtime cost. Reference counting is not for free. – juanchopanza Aug 01 '14 at 21:29
0

shared_ptr is a class type, when the instance of shared_ptr is destroyed, the destructor of shared_ptr will free the memory, this is not GC.

Matt
  • 6,010
  • 25
  • 36
  • More precisely, when an instance of `shared_ptr` is destroyed, its destructor will decrement a reference count for the pointed-to object. If that ref count becomes zero, it will destroy the object. – Fred Larson Aug 01 '14 at 17:53