C++ cstdlib atexit


The C++ <cstdlib> atexit function registers the function pointed by the parameter and call it at normal program termination.The declaration of the function is shown below.

int atexit(void (*func )(void)) noexcept;

Parameters:
(*func )(void) -A pointer to function which does not return any value and also does not accept any argument (except void type).

Return type
int – Returns 0 if it succeeds,else it returns some non-zero value.

Some points to note:

i) This function is only called if the program terminates normally,if ‘abort’ is called this function is not called.And also this function does not pass any exception.

ii) If ‘atexit’ is called after the call to ‘exit’ function it is not specified whether the function is called.

iii) The implementation shall support the registration of at least 32 functions.

iv) If the function accept any argument or return any type other than the ‘void’ type you will get an error.

v) If many functions are registered then the functions are called in the reverse order of their registration.This simply means the function that appear first as the ‘atexit’ parameter is called last.A code example for this case is provided below.

vi) The ‘atexit’ does not introduce data races.

Link : C++ cstdlib exit function

Code example

void func( )
{
cout<< “func called \n” ;
}

int main( )
{
cout<< “Calling atexit”;

atexit( func );

cin.get( );
return 0;
}

Output

Calling atexit
func called





A more exhaustive code example is given below.

Code example

#include <iostream>
#include <cstdlib>

using namespace std;

class Aa
{
public:
  Aa() { cout<< “Aa constructor called”; }

  void func( ) { cout<< “Aa func called”; }

  ~Aa() { cout<< “Aa destructor called”; }
};

int ifunc() { }

void funci( int ) { }

void func( ) { cout<<“func called”; }

int main( )
{
Aa a;

//atexit( ifunc ) ; //error ‘ifunc’ returns ‘int’ type
//atexit( funci ) ; //error ‘funci’ accept ‘int’ type argument
//atexit( a.func ) ; //error,calling member function of Aa

atexit( func ); ///work fine

cin.get( );
return 0;
}

Output

Aa constructor called
Aa destructor called
func called

As you can see the destructor of Aa class is called appropriately.This shows that calling atexit is secure.

Another code example is provided below to check the order of the functions called that are registered by the ‘atexit’ function.

Code example

void func1( ) { cout<<“func1 called \n”; }

void func2( ) { cout<< “func2 called \n”; }

int main( )
{
atexit( func1 );

atexit( func2 );

cin.get( );
return 0;
}

Output

func2 called
func1 called