Improve the classs cleanup code when using valgrind