Additional Termination Considerations

You can terminate a C++ program by using exit, return, or abort. You can add exit processing using the atexit function. These are discussed in the following sections.

Using exit or return

When you call exit or execute a return statement from main, static objects are destroyed in the reverse order of their initialization. This example shows how such initialization and cleanup works:

#include <stdio.h>

class ShowData

{

public:

// Constructor opens a file.

ShowData( const char *szDev )

{

OutputDev = fopen( szDev, "w" );

}

// Destructor closes the file.

~ShowData() { fclose( OutputDev ); }

// Disp method shows a string on the output device.

void Disp( char *szData )

{

fputs( szData, OutputDev );

}

private:

FILE *OutputDev;

};

// Define a static object of type ShowData. The output device

// selected is "CON" -- the standard output device.

ShowData sd1 = "CON";

// Define another static object of type ShowData. The output

// is directed to a file called "HELLO.DAT"

ShowData sd2 = "hello.dat";

int main()

{

sd1.Disp( "hello to default device\n" );

sd2.Disp( "hello to file hello.dat\n" );

return 0;

}

In the preceding example, the static objects sd1 and sd2 are created and initialized before entry to main. After this program terminates using the return statement, first sd2, then sd1 is destroyed. The destructor for the ShowData class closes the files associated with these static objects. (For more information about initialization, constructors, and destructors, see Chapter 11, “Special Member Functions.”)

Note:

Another way to write this code is to declare the ShowData objects with block scope, allowing them to be destroyed when they go out of scope:

int main()

{

ShowData sd1, sd2( "hello.dat" );

sd1.Disp( "hello to default device\n" );

sd2.Disp( "hello to file hello.dat\n" );

return 0;

}

Using atexit

The atexit function allows you to specify an exit-processing function that executes prior to program termination. No global static objects initialized prior to the call to atexit are destroyed prior to execution of the exit-processing function.

Using abort

Calling the abort function causes immediate termination. It bypasses the normal destruction process for initialized global static objects. It also bypasses any special processing that was specified using the atexit function.