3

I'm not sure whether it's strict to say, but I'd like to treat shared ptr as a garbage collection strategy.

I've two questions here:

  1. When is shared ptr appropriate for garbage collection; and when other strategies such as mark-sweep?
  2. Is there any lib implemented shared ptr in C?

Thanks.

MByD
  • 135,866
  • 28
  • 264
  • 277
pipipi
  • 501
  • 1
  • 3
  • 11
  • What do you mean by treating shared ptr as a garbage collection strategy? Do you mean comparing the shared pointers (termed Reference Counting in the GC world) and mark-sweep? I think boost implements shared pointers: http://www.boost.org/doc/libs/1_49_0/libs/smart_ptr/shared_ptr.htm. Read more about this here: http://stackoverflow.com/questions/417481/pointers-smart-pointers-or-shared-pointers – smichak May 07 '12 at 07:53
  • @smichak Yes, I'd like to see some comparisons among different garbage collection techniques for Q1. – pipipi May 07 '12 at 08:09

2 Answers2

3

If you want garbage collection in C, have a look at the Hans Boehm garbage collection library.

Shared ptr removes much of the necessity of handling object deletion, but has a number of complications: only one shared pointer can hold the pointer at a time. You might want to look also at Boost's smart_ptr pointer handling and related classes.

But shared_ptr, and Boost, is C++. You will struggle to achieve this in C: shared_ptr relies on operator overloading to achieve its magic. Without operator overloading, you have no way of knowing if someone, somewhere, is holding a copy of your pointer. (This is a problem also in C++, but the operator overloading reduces the risk if you use shared_ptr throughout your code.)

I would definitely recommend Hans Boehm instead.

craigmj
  • 4,827
  • 2
  • 18
  • 22
2

There are a few good articles that talk about this:

Garbage Collection Synopsis, and C++

Previous Similar Question on StackOverflow: Garbage collection vs. shared pointers

I would also recommend you look into scoped_ptr. Here's the differences: shared_ptr vs scoped_ptr

Community
  • 1
  • 1
Aayush Kumar
  • 1,618
  • 1
  • 11
  • 31