14

Because of my noob reputation, I cannot reply to this Thread, in specific the accepted answer:

I never used boost::intrusive smart pointers, but if you would use shared_ptr smart pointers, you could use weak_ptr objects for your cache.

Those weak_ptr pointers do not count as a reference when the system decides to free their memory, but can be used to retrieve a shared_ptr as long as the object has not been deleted yet.

This is certainly an intuitive idea, however, the C++ standard does not support comparison of weak_ptrs, so it cannot be used as key for associative containers. This could be circumvented by implementing a comparison operator for weak_ptrs:

template<class Ty1, class Ty2>
    bool operator<(
        const weak_ptr<Ty1>& _Left,
        const weak_ptr<Ty2>& _Right
    );

The problem with this solution is that

(1) the comparison operator has to obtain ownership for every comparison (i.e. creating shared_ptrs from the weak_ptr refs)

(2) the weak_ptr is not erased from the cache when the last shared_ptr that manages the resource is destroyed, but an expired weak_ptr is kept in the cache.

For (2), we could provide a custom destructor (DeleteThread), however, this would require again to create a weak_ptr from the T* that is to delete, which can then be used to erase the weak_ptr from the cache.

My question would be if there is any better approach to a cache using smart pointers (I am using the VC100 compiler, no boost), or do I simply not get it?

Cheers, Daniel

Community
  • 1
  • 1
dwn
  • 413
  • 3
  • 12
  • 1
    You can't change the key of any key-based container!!! It has to be immutable! You could have some custom delete-the-last which reaches out & removes the entry from your container. But having a key change values while in a container is a huge no-no. – Mordachai Dec 09 '11 at 15:33
  • That is exactly the problem, I would need to provide a custom deleter that erases the object from the cache to avoid having an expired pointer in the cache. Or are you talking more generally, since the ref-count is changing? – dwn Dec 10 '11 at 14:33

2 Answers2

4

A possible solution for what you want to achieve might be

Lets say T is your object and shared_ptr<T> is your shared ptr

  1. Only have regular T* in your cache.
  2. Have a custom deleter for your shared_ptr<T>
  3. Have your custom deleter erase your T* from the cache upon delete.

This way the cache doesn't increase the ref count of your shared_ptr<T> but is notified when the ref count reaches 0.

struct Obj{};

struct Deleter
{
    std::set<Obj*>& mSet;
    Deleter( std::set<Obj*>& setIn  )
        : mSet(setIn) {}

    void operator()( Obj* pToDelete )
    {
        mSet.erase( pToDelete );
        delete pToDelete;
    }
};

int main ()
{

    std::set< Obj* > mySet;
    Deleter d(mySet);
    std::shared_ptr<Obj> obj1 = std::shared_ptr<Obj>( new Obj() , d );
    mySet.insert( obj1.get() );
    std::shared_ptr<Obj> obj2 = std::shared_ptr<Obj>( new Obj() , d );
    mySet.insert( obj2.get() );

    //Here set should have two elements
    obj1 = 0;
    //Here set will only have one element

    return 42;
}
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
  • Thanks parapura, the solution is nice and what I wanted. I think you have a small mistake: `std::set mSet;` should be a reference. – dwn Dec 09 '11 at 15:27
  • @Thanks.... Of course in my hurry I didn't test it fully yet... edited and corrected my mistake. I am not sure about the **Deleter functor** signature either. Seems to work under VS 2011 – parapura rajkumar Dec 09 '11 at 15:29
  • 2
    Interesting... but **wrong**. There is a subtle difference between a `Cache` and a `Factory`. Your implementation is fine *for a* `Factory`. However, a `Cache` is supposed to be able to return the same object several times, and there is no way to create a copy of the `shared_ptr` from the raw `T*`, so you're stuck... (and creating a new `shared_ptr` is the shortest road to hell). – Matthieu M. Dec 09 '11 at 17:25
  • @MatthieuM. this would be trivially fixed (at least in the single thread case) if boost weren't ruled out too - [by this](http://www.boost.org/doc/libs/release/libs/smart_ptr/enable_shared_from_this.html). As far as I'm aware there's no equivalent in `std::shared_ptr` though. – Flexo Dec 10 '11 at 00:40
  • @awoodland: // 20.7.2.4, class template enable_shared_from_this – Matthieu M. Dec 10 '11 at 11:34
  • @parapurarajkumar "_I am not sure about the Deleter functor signature either._" "D shall be CopyConstructible. The copy constructor and destructor of D shall not throw exceptions. The expression d(p) shall be well formed, shall have well defined behavior, and shall not throw exceptions." This seems OK. – curiousguy Dec 18 '11 at 16:28
  • @awoodland "_this would be trivially fixed (at least in the single thread case) if boost weren't ruled out too_" You have to understand that `enable_shared_from_this` is just a base containing a `weak_ptr`, which is recognised by `shared_ptr` constructor, and enabled at `shared_ptr` construction time. It is important to understand that `enable_shared_from_this` is nothing more; in particular, it has `weak_ptr` semantics, only the `weak_ptr` "points to" `this` (except, `weak_ptr` is not a pointer). – curiousguy Dec 18 '11 at 16:34
  • @curiousguy - that's exactly what you want in a cache though. If the weak_ptr is invalid then you're calling the deleter anyway so shouldn't be in a position to call shared_from_this. – Flexo Dec 18 '11 at 18:10
  • @awoodland This is probably one of the (very few) valid uses of `weak_ptr`. – curiousguy Dec 18 '11 at 21:49
2

The thing is, your Cache is not addressed by the object cached itself, otherwise it would be about useless.

The idea of a Cache is to avoid some computation, so the index will be the parameters of the computation, which will directly map to the result if already present.

Now, you might actually need a second index, to remove objects from the cache, but it is not mandatory. There are certainly other strategies available.

If you really want to remove objects from the cache as soon as they are not used anywhere else in the application, then, effectively, you could use a secondary index. The idea here though will be to index according to T*, not weak_ptr<T>, but to keep weak_ptr<T> around, because otherwise you cannot create a new shared_ptr on the same reference count.

The exact structure depends on whether the parameters of the computation are hard to recompute after the fact, if they are, a simple solution is:

template <typename K, typename V>
class Cache: boost::enable_shared_from_this<Cache>
{
  typedef std::map<K, boost::weak_ptr<V>> KeyValueMap;
  typedef std::map<V*, KeyValueMap::iterator> DeleterMap;

  struct Deleter {
    Deleter(boost::weak_ptr<Cache> c): _cache(c) {}

    void operator()(V* v) {
      boost::shared_ptr<Cache> cache = _cache.lock();
      if (cache.get() == 0) { delete v; return; }

      DeleterMap::iterator it = _cache.delmap.find(v);
      _cache.key2val.erase(it->second);
      _delmap.erase(it);
      delete v;
    }

    boost::weak_ptr<Cache> _cache;
  }; // Deleter

public:
  size_t size() const { return _key2val.size(); }

  boost::shared_ptr<V> get(K const& k) const {
    KeyValueMap::const_iterator it = _key2val.find(k);
    if (it != _key2val.end()) { return boost::shared_ptr<V>(it->second); }

    // need to create it
    boost::shared_ptr<V> ptr(new_value(k),
        Deleter(boost::shared_from_this()));

    KeyValueMap::iterator kv = _key2val.insert(std::make_pair(k, ptr)).first;
    _delmap.insert(std::make_pair(ptr.get(), kv));

    return ptr;
  }


private:
  mutable KeyValueMap _key2val;
  mutable DeleterMap _delmap;
};

Note the special difficult: the pointer might outlive the Cache, so we need some trick here...

And for your information, while it seems feasible, I am not at all confident in this code: untested, unproven, bla, bla ;)

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • The solution is nice, in specific the `DeleterMap` is what I was looking for. But I disagree on the point that the cached object is not the key of the cache: the idea is to have a cache of pointers which ensures that there are no 2 pointers that are equal when derefenced (use dereferencing less comparison for sorting). This allows me to reuse (immutable) object pointers across multiple objects to safe memory. Still, I can simply use your more generic approach `typedef std::map> KeyValueMap;` and replace it with a `std::set`. – dwn Dec 10 '11 at 15:50
  • I also did not test it yet, but think the line `if (cache.get() == 0) { delete v; }` should be `if (_cache.get() == 0) { delete v; return; }` – dwn Dec 10 '11 at 15:52
  • @dawn: regarding your particular situation: indeed, adapt to your own needs :) regarding your remark... doh! Thanks, I fixed it :) – Matthieu M. Dec 10 '11 at 18:06
  • "`if (cache.get() == 0)`" Never true! "`boost::shared_ptr cache(_cache);`" "Throws: bad_weak_ptr when r.expired()." – curiousguy Dec 18 '11 at 16:36
  • @curiousguy: thanks for caching this, I had meant to use `lock`... one would wonder why both do not have the same behavior :x – Matthieu M. Dec 19 '11 at 19:43