Listing 4: Uses internal state to track a resource

// destroy6.cpp
#include <stdio.h>

main()
{
    void f(const char*);
    try
    {
        f("file1.dat");
    }
    catch(int)
    {
        puts("Caught exception");
    }
}

void f(const char *fname)
{
    class File
    {
        FILE* f;
    public:
        File(const char* fname,
             const char* mode)
        {
            f = fopen(fname, mode);
        }
        ~File()
        {
            if (f)
            {
                fclose(f);
                puts("File closed");
            }
        }
        operator void*() const
        {
            return f ? (void *) this : 0;
        }
    };
    File x(fname,"r");
    if (x)
    {
        // Use file here
        puts("Processing file...");
    }
    throw 1;
}

// Output:
Processing file...
File closed
Caught exception
//End of File