Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference counting (without storing any data)

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

like image 982
user2052436 Avatar asked Dec 26 '22 15:12

user2052436


2 Answers

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

like image 200
Sebastian Redl Avatar answered Jan 08 '23 03:01

Sebastian Redl


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

This does precisely what you want.

Live example

like image 31
Angew is no longer proud of SO Avatar answered Jan 08 '23 03:01

Angew is no longer proud of SO