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
A simple atomic<int>
should suffice. I don't see any need for anything more complex.
std::shared_ptr<void> p(nullptr, MyDeleter());
This does precisely what you want.
Live example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With