move push_tmp_mem and friends into restore_mem
make restore_mem a RAII class
add some protection against heap allocating restore_mem