www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/11/03/08:58:17

Message-Id: <3.0.16.19971103155255.384f8828@hem1.passagen.se>
Date: Mon, 03 Nov 1997 15:53:36 -0500
To: djgpp AT delorie DOT com
From: Peter Palotas <blizzar AT hem1 DOT passagen DOT se>
Subject: Writing to a file from dtor doesn't work!
Mime-Version: 1.0

Take a look at the following tiny bit of code:

#include <stdio.h>
class A 
{
private:
	FILE *fl;
public:
	A(void)
        {
        	fl = fopen("test.log", "wt");
        	fprintf(fl, "In A constructor\n");
        }

        ~A(void)
        {
         	fprintf(fl, "In A destructor\n");
                fclose(fl);
        }
};

A a;

int main(void)
{
	return 0;
}

Okay, now everyone probably sees what this should do. It should write the
two lines "In A constructor" and "In A destructor" to the file "test.log"
(provided that it successfully can open the file, but since this is only a
test program, I don't bother checking that.

Well, the problem is that if you declare an object of 'A' at global scope,
like I did in this example, nothing gets written in the destructor! i.e.
the file only contains one line; "In A constructor".

Declaring 'a' (an object of 'A') inside main() however makes everything
work as it's supposed to.  (Reopening the file in the destructor also works
fine, so it seems as if the file is closed before we reach the destructor
or something?)

Now is this a bug, or is it normal behaviour? Becuase it doesn't seem
normal to me, and I haven't found any documentation on it either, so any
help solving this would be appreciated.


-- Peter Palotas alias Blizzar -- blizzar AT hem1 DOT passagen DOT se --

*****************************************************
* A brief description of DJGPP:                     *
* NEVER BEFORE HAS SO FEW DONE SO MUCH FOR SO MANY! *
*****************************************************

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019