Yes, I agree that local object are not destroyed as in the following case:
Example 1: Local FOO Using Return
Code:
#include <stdlib.h>
class foo {
public:
int x;
foo( int i ) {
x = i;
}
void print( void ) {
printf( "Hello, foo x val=%d\n", x );
}
~foo(){
printf( "foo destructor\n" );
}
};
int main ( void ) {
foo FOO( 1);
FOO.print();
return ( EXIT_SUCCESS );
}
###############OUTPUT###############
# ./foo
Hello, foo x val=0
foo destructor
Example 2: Local FOO Using Exit
Code:
#include <stdlib.h>
class foo {
public:
int x;
foo( int i ) {
x = i;
}
void print( void ) {
printf( "Hello, foo x val=%d\n", x );
}
~foo(){
printf( "foo destructor\n" );
}
};
int main ( void ) {
foo FOO( 1 );
FOO.print();
exit ( EXIT_SUCCESS );
}
###############OUTPUT###############
# ./foo
Hello, foo x val=0
Now let me clean this up a little to simulate a more realistic approach:
Example 3: Global FOO Using Return
Code:
//FileName: foo.cc
#include "foo2.h"
foo FOO(1); // FOO defined at a global level.
int main ( void ) {
FOO.print();
return ( EXIT_SUCCESS );
}
// File Name: foo2.h
#ifndef _FOO2_H_
#define _FOO2_H_
#include <stdlib.h>
class foo {
public:
int x;
foo( int i );
~foo();
void print( void );
};
#endif
// File Name: foo2.cc
#include "foo2.h"
foo::foo( int i ) {
x = i;
}
void foo::print( void ) {
printf( "Hello, foo x val=%d\n", x );
}
foo::~foo(){
printf( "foo destructor\n" );
}
###############OUTPUT###############
# ./foo
Hello, foo x val=1
foo destructor
Example 4: Global FOO Using Exit
Code:
//FileName: foo.cc
#include "foo2.h"
foo FOO(1); // FOO defined at a global level.
int main ( void ) {
FOO.print();
exit ( EXIT_SUCCESS );
}
// File Name: foo2.h
#ifndef _FOO2_H_
#define _FOO2_H_
#include <stdlib.h>
class foo {
public:
int x;
foo( int i );
~foo();
void print( void );
};
#endif
// File Name: foo2.cc
#include "foo2.h"
foo::foo( int i ) {
x = i;
}
void foo::print( void ) {
printf( "Hello, foo x val=%d\n", x );
}
foo::~foo(){
printf( "foo destructor\n" );
}
###############OUTPUT###############
# ./foo
Hello, foo x val=1
foo destructor
And if FOO was created using foo FOO = new foo( 1 ) then niether return nor exit will call the destructor. One would need to do something like if ( FOO ) { delete FOO; } .
So, with this being said, I understand your point and see the validity in your statements. Everything must be put into the context of what you are accomplishing. If the objects are only local object then yes return should be invoked however, if the objects are global or created with new then it really does not matter and should be left to the coders choice. I say this because if the object is global then both return and exit invoke the destructor. If the object is created using new then niether return nor exit will invoke the destructor; the memory must be freed using delete.
This has been a great topic and has led me to look into a few of the elements of C++ that I have taken for granted. I can see the merit in the argument for the use of return.
DeadPoet.