How to delete at the end of an OpenGL program ???

I’ve got a simple opengl program, in a file my_app.cpp
I declare in the global scope a pointer:

my_object* obj = new my_object();

I’d like to know WHEN I can delete this object ???
I tried it:

int main(int argc, char *argv[])
glutInit(&argc, argv);    
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT);
    glutInitWindowPosition(0, 0);


    glutTimerFunc(elapsedUSecs, timerCallback, 0);


    delete obj; // I NEVER REACH THIS LINE !!!

    return 0;

I think it’s very easy, so anyone has got the anwer ?

thanks a lot.

You can use from the mouse or keyboard functions to delete the object. As an example:
void mouse( int btn, int state, int x, int y )
if( btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN )

And your ExitFromProgram can be in this form:
void ExitFromProgram()
if( object )
free object;

In your previous code, you never can free the object, since it has been called after your glutMainLoop().If you free the object before the glutMainLoop(), you never can use from that object in your program, since it is deleted in the first loop.none-glut functions in your main function are executed only in the first loop.


the glut doc advises to use

int on_exit(void (*function)(int , void *), void *arg);

from <stdlib.h> to register a user function which will be called when the app exits.



class foo {
 public:                foo() { printf("	creating foo
"); };
                        ~foo() { printf("	deleting foo
"); }; };

 foo    *new_foo;

 void my_exit(int i, void *ptr) {

 delete(new_foo); }

int main(int argc, char *argv[]) {

 new_foo = new foo;
 on_exit(my_exit, NULL); }
//      gcc -o fooclass

prefer use at_exit instead of on_exit for c++ programs.

ok. but why?

at_exit doesn’t work, but on_exit does.

RigidBody, simply because atexit has been redefined in the C++ standard library, so might not provokes some mistakes due to a C-only function call. As you know C and C++ are no longer 100% compatible. This is almost true for the standard library.

VinceDeNice, I don’t know why at_exit doesn’t work, maybe because it is called atexit and not at_exit :slight_smile: . It’s defined in cstdlib if I’m not wrong.

I just searched in MSDN. Yes it is atexit and is defined at <stdlib.h> :slight_smile:
LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version