Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About shared ptr

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.

like image 474
pipipi Avatar asked Dec 01 '25 22:12

pipipi


1 Answers

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.

like image 113
craigmj Avatar answered Dec 03 '25 12:12

craigmj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!