Reference counting (without storing any data)

I need to have a common counter in my class (to call some function when the counter goes to zero). I can use shared_ptr<char>with a deleter for this, but this approach has the overhead of highlighting the unnecessary charand storing a pointer to it.

Basically, I need a reference counting part shared_ptr. I do not see how I can use shared_ptrand avoid this overhead.

Is there a portable C ++ 11 implementation (i.e., only using standard C ++ 11 and stdexplicit mutexes, etc.) of common counters?

PS. The counter is not unique to the entire class. I can have objects a1, a2, a3 of my class that use the same counter. And b1, b2, b3, which use different counters. Therefore, when the last of a1, a2, a3 goes out of scope, something should happen (related to a1, a2, a3). When the last of b1, b2, b3 goes out of scope, something must happen (related to b1, b2, b3).

thanks

+4
source share
3 answers
std::shared_ptr<void> p(nullptr, MyDeleter());

It does exactly what you want.

Living example

+3
source

Simple enough atomic<int>. I do not see anything more complicated.

+6
source

Give it a try std::shared_ptr<void> ptr = std::make_shared<char>();. It has single-byte overhead (which is probably rounded for alignment reasons), but the highlighted one charis in the same block as the reference counting implementation when you use make_sharedto create shared_ptr.

Another approach would be to use the on exit 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 deleterand replaces it with overhead std::function.

+1
source

All Articles