Listing 7: Fixes the memory leak with auto_ptr
// destroy9.cpp
#include <stdio.h>
#include <memory> // For auto_ptr
using namespace std;
class File
{
FILE* f;
public:
File(const char* fname, const char* mode)
{
f = fopen(fname, mode);
if (!f)
throw 1;
}
~File()
{
if (f)
{
fclose(f);
puts("File closed");
}
}
};
main()
{
void f(const char*);
try
{
f("file1.dat");
}
catch(int x)
{
printf("Caught exception: %d\n",x);
}
}
void f(const char* fname)
{
auto_ptr<File> xp = new File(fname,"r");
puts("Processing file...");
throw 2;
}
// Output:
Processing file...
File closed
Caught exception: 2
//End of File