c++11 - Run a function when number of references decrease in shared_ptr -


i developing cache , need know when object expired. possible run function when reference counter of shared_ptr decrease?

std::shared_ptr< myclass > p1 = std::make_shared( myclass() ); std::shared_ptr< myclass > p2 = p1; // p1.use_count() = 2 p2.reset(); // [ run function ] p1.use_count() = 1 

you can't have function called every time reference count decreases, can have 1 called when hits zero. passing "custom deleter" shared_ptr constructor (you can't use make_shared utility this); deleter callable object responsible being passed, , deleting, shared object.

example:

#include <iostream> #include <memory> using namespace std;  void deleteint(int* i) {     std::cout << "deleting " << *i << std::endl;     delete i; }  int main() {     std::shared_ptr<int> ptr(new int(3), &deleteint); // refcount 1     auto ptr2 = ptr; // refcount 2     ptr.reset(); // refcount 1     ptr2.reset(); // refcount 0, deleter called     return 0; } 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -