垃圾收集与共享指针 [英] Garbage collection vs. shared pointers

查看:177
本文介绍了垃圾收集与共享指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

共享指针(例如boost :: shared_ptr或新std :: shared_ptr)和垃圾收集方法(例如在Java或C#中实现的方法)之间有什么区别?我理解它的方式是,共享指针记录变量指向资源的次数,并在计数达到零时自动破坏资源。然而,我的理解是垃圾收集器也管理内存资源,但需要额外的资源来确定一个对象是否仍然被引用,并不一定立即破坏资源。



我的假设是否正确,并且在使用垃圾收集器和共享指针之间还有其他区别吗?另外,为什么有人会在共享指针上使用垃圾回收器,如果他们执行类似的任务,但具有不同的性能数字?解析方案

正如你所注意到的,主要区别在于资源何时被释放/销毁。



GC可能派上用场的一个好处是如果你有资源需要很长时间才能发布。对于短的程序生命周期,最好让资源悬而未决并最终清理它们。如果达到资源限制,则GC可以采取行动释放其中一些资源。另一方面,共享指针在引用计数达到零后立即释放它们的资源。这对于需要花费时间的资源的频繁获取 - 释放周期来说可能是昂贵的。另一方面,在一些垃圾收集实现中,垃圾收集要求整个程序暂停执行,同时检查内存,移动并释放内存。有更聪明的实现,但没有一个是完美的。


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 C#)? The way I understand it, shared pointers keep track of how many times variables points to the resource and will automatically destruct the resource when the count reaches zero. However, my understanding is that the garbage collector also manages memory resources, but requires additional resources to determine if an object is still being referred to and doesn't necessarily destruct the resource immediately.

Am I correct in my assumptions, and are there any other differences between using garbage collectors and shared pointers? Also, why would anyone ever used a garbage collector over a shared pointer if they perform similar tasks but with varying performance figures?

解决方案

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.

这篇关于垃圾收集与共享指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆