does know of compiler c++ supports garbage collection. know considering c++11 didn't implement it.
one of most-often heard of approaches use hans boehm's gc, can plugged c++. of course, alternative use smart pointers keep track of use of objects.
for upvoted "who needs this" comment, answer can more expensive:
- imagine fork() program , start adjusting refcounters in objects remain constant otherwise. cause performance overhead because means os can't share memory between 2 processes, i.e. breaks copy-on-write. in cases, can mean os has swap in memory copy , adjust reference counters.
- another example suggested
boost::shared_ptr
. each of these has additional allocation overhead in order store reference counter, weak reference counter , deleter. doesn't come free either. further, instance thereof has twice size of pointer. - then, if use normal size_t refcounter , built-in increment/decrement, code isn't multithreading safe. however, if use atomic integers, incrementing , decrementing takes more time flush caches , because disallows reordering. remember, every time copy such pointer, have increment reference counter. every time 1 instance destroyed, have decrement counter again. maintaining reference count can accumulate higher overhead using mark-and-sweep gc count references , then.
- lastly, refcounted pointers need programmer actively consider possibility of cycles. gcs can detect , break cycles automatically.
if keep above in mind, gc alternative. have disadvantages, non-deterministic cleanup, java , c# show can live , there nothing keeps programming in places need it.
Comments
Post a Comment