Q:

Run a function when number of references decrease in shared_ptr

I am developing a cache and I need to know when an object expired.
Is possible run a function when the reference counter of a 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

A:

You can't have a function called every time the reference count decreases, but you can have one called when it hits zero. You do this by passing a "custom deleter" to the shared_ptr constructor (you can't use the make_shared utility for this); the deleter is a callable object which is responsible for being passed, and deleting, the 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 now 1
    auto ptr2 = ptr; // refcount now 2
    ptr.reset(); // refcount now 1
    ptr2.reset(); // refcount now 0, deleter called
    return 0;
}

