Testing ScopeGuard from CUJ article: SG destructor not called on exceptions??

From: Vikram Paranjape (usenet.20.vsp_at_spamgourmet.com)
Date: 02/29/04


Date: 29 Feb 2004 06:38:46 -0800

Hi,

I wrote a small test script to utilize the ScopeGuard class from the
Dec 2000 CUJ article.

I noted that my cleanup function was being called on normal block
exit, but not on calling a function I wrote to throw an exception.

#include <iostream>
#include <exception>
#include "ScopeGuard.h"

using namespace std;

void CloseFile(FILE* file)
{
   cout << "Closing file" << endl;
   fclose(file);
   cout << "Closed file" << endl;
}

void Throw(void)
{
   throw std::exception();
}

int testScopeGuard (void)
{
   //Open a file that we don't intend to close
   FILE* file = fopen("abc.txt", "a+");
   ON_BLOCK_EXIT(CloseFile, file);
   cout << "Guard made" << endl;
   Throw();
}

When I comment out the Throw() call, the function CloseFile is called
and I do get a log like :
Guard made
Closing file
Closed file

However, when I leave the Throw() call in, I get a log like:
Guard made
Aborted (core dumped)

I am using g++ on cygwin :
bash-2.05b$ g++ --version
g++ (GCC) 3.3.1 (cygming special)

Does this mean that on encountering an exception, the ScopeGuard
object made by ON_BLOCK_EXIT is not being destroyed?

Regards,
Vikram



Relevant Pages