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.
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.
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.
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: Of course I'm talking of a situation when caching is actually useful, because the objects are costly to construct (think of several access to a database and queries of a network), yet there are too many to keep them all forever.