Garbage collection vs. shared pointers

前端 未结 3 1959
栀梦
栀梦 2020-12-15 06:13

What are the differences between shared pointers (such as boost::shared_ptr or the new std::shared_ptr) and garbage collection methods (such as those implemented in Java or

3条回答
  •  旧时难觅i
    2020-12-15 06:27

    The main difference lies, as you noted, in when the resource is released/destroyed.

    One advantage where a GC might come in handy is if you have resources that take a long time to be released. For a short program lifetime, it might be nice to leave the resources dangling and have them cleaned up in the end. If resource limits are reached, then the GC can act to release some of them. Shared pointers, on the other hand, release their resources as soon as the reference count hits zero. This could be costly for frequent acquisition-release cycles of a resource with costly time requirements.

    On the other hand, in some garbage collection implementations, garbage collection requires that the whole program pause its execution while memory is examined, moved around, and freed. There are smarter implementations, but none are perfect.

提交回复
热议问题