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

From: Alf P. Steinbach (alfps_at_start.no)
Date: 02/29/04


Date: Sun, 29 Feb 2004 14:59:37 GMT


* usenet.20.vsp@spamgourmet.com (Vikram Paranjape) schriebt:
>
> 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();

Insert dummy 'return 0;' here to satisfy comp

> }
>
> 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

Have you tried catching the exception in main?

It might be that the std::cout isn't flushed like it should be.

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

With MingW g++ 3.2.3 and exception catching in main there is seemingly no
problem:

C:\...\test> g++ --version
g++ (GCC) 3.2.3 (mingw special 20030504-1)
Copyright (C) 2002 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

C:\...\test> g++ -pedantic -ansi -o main.exe main.cpp

C:\...\test> main
Guard made
Closing file
Closed file
! St9exception

C:\...\test> _

It also compiles and runs fine with Visual C++ 7.1, when the appropriate
fix for the MSVC compiler bug is made in [ScopeGuard.h], namely

#ifdef _MSC_VER
    #define ANONYMOUS_VARIABLE(str) CONCATENATE(str, __COUNTER__)
#else
    #define ANONYMOUS_VARIABLE(str) CONCATENATE(str, __LINE__)
#endif

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

Probably not.

Try a debugger, try catching that exception in main.



Relevant Pages