سؤال

I need to have a shared counter in my class (to call some function when counter goes to zero). I can use a shared_ptr<char> with a deleter for that, but this approach has an overhead of allocating an unneeded char and keeping a pointer to it.

Basically, I need reference counting part of shared_ptr. I do not see how I can utilize shared_ptr and avoid this overhead.

Is there a portable C++11 implementation (i.e., using standard c++11 and std only, no explicit mutexes, etc.) of shared counters?

PS. Counter is not unique to the entire class. I may have objects a1, a2, a3 of my class that share same counter. And b1, b2, b3 that share different counter. So when last one of a1, a2, a3 goes out of scope something (related to a1, a2, a3) should happen. When last one of b1, b2, b3 goes out of scope, something (related to b1, b2, b3) should happen.

Thanks

هل كانت مفيدة؟

المحلول 2

std::shared_ptr<void> p(nullptr, MyDeleter());

This does precisely what you want.

Live example

نصائح أخرى

A simple atomic<int> should suffice. I don't see any need for anything more complex.

Try std::shared_ptr<void> ptr = std::make_shared<char>();. This does have a single byte overhead (which probably rounds up for alignment reasons), but the char allocated is in the same block as the reference counting implementation when you use make_shared to create your shared_ptr.

Another approach would be to use an "at exit scope" object:

struct at_exit_scope {
  std::function<void()> f;
  ~at_exit_scope() { f(); }
  template<typename F>
  at_exit_scope( F&& f_ ):f(std::forward<F>(f_)) {}
  at_exit_scope() = delete;
  at_exit_scope(at_exit_scope const&) = delete;
};

then do a shared_ptr<at_exit_scope> ptr = std::make_shared<at_exit_scope>( [=]{ /* code */ } ). This eliminates the need for a deleter, and replaces it with a std::function's overhead.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top