C ++中的软(not:weak)引用 - 是可能吗?是否有实现? [英] Soft (not: weak) references in C++ - Is it possible? Is there an implementation?

查看:191
本文介绍了C ++中的软(not:weak)引用 - 是可能吗?是否有实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我使用 boost :: shared_ptr boost :: weak_ptr 不再需要。我知道这些工作与引用计数。

In C++ I'm using boost::shared_ptr and boost::weak_ptr to automatically delete objects that are no longer needed. I know these work with reference counting.

在Java中,内存由垃圾回收器管理,它考虑内置对象引用 strong WeakReference weak SoftReference (可能由GC收集,但也可以在GC中生存),这对于缓存对象有一段时间是非常方便的,但是一旦空闲内存变得很低,就立即将它们丢弃。

In Java, memory is managed by a garbage collector, which consideres the built-in object references as strong, WeakReference as weak and SoftReference as something in between (may be collected by the GC, but may as well survive the GC), which is really handy for caching objects for some time, but throwing them away as soon as free memory is getting low.

现在我回到C ++,我错过了软引用的舒适性。我不知道参考点计算是否可行的软参考。当对对象的最后一个强引用被清除,并且仍然有一个 soft 引用时,何时会被删除?我可以想到一些计划,但是没有一个对我来说很聪明。

So now I'm back in C++ and I miss the comfort of having soft references. I wonder if soft referencing is practicable with reference counting at all. When the last strong reference to an object is cleared, and there remains a soft reference, when would it be deleted after all? I could think of some schemes, but none of them seem clever to me.

为了在软引用和引用计数有适当的语义的情况下,我不知道这是否已经被实现,可能在某种程度上甚至与 boost :: shared_ptr (或C ++ TR1等效 std :: shared_ptr

Just in case there are proper semantics for soft references along with reference counting, I wonder if this has already been implemented, maybe in a way that's even compatible with boost::shared_ptr (or the C++ TR1 equivalent std::shared_ptr for that matter).

如果这两个问题的答案都是否定的,那么对象缓存方案中的替代方法是什么?

If the answer to both questions is no, what are the alternatives in an object caching scenario?

EDIT:
当然,我说的是缓存实际上很有用的情况,因为对象是昂贵的

推荐答案

为了模仿这种在C ++中的行为, ,您必须构建一个内存感知的引用缓存,该缓存在对象上持有强引用,您的应用程序的其余部分将会弱化 。当缓存确定应用程序正在划分其内存使用上限 - 或任何其他约束条件时,它将释放强引用,放弃集合的对象(达到零引用计数),并允许稍后使用的弱引用检测到无效。

In order to mimic this behavior in C++, you'd have to build a memory-aware reference cache that held strong references on objects that the rest of your application would hold weakly. When the cache determined that the application was scratching its memory usage ceiling — or any other constraining criteria — it would release the strong references, surrendering the objects for "collection" (reaching the zero reference count) and allowing the weak references in use to later detect invalidation.

这篇关于C ++中的软(not:weak)引用 - 是可能吗?是否有实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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