Factor out all of the C++ refcounting hooks.

Move everything into a scoped RAII object, it's much nicer.