C ++: the best way to destroy static things

When I have a class containing static things, how can I free memory at the end of the application in the best way?

foo.h

class GLUtesselator;

class Foo
{
private:
    static GLUtesselator *tess;
public:
    Foo();
    virtual ~Foo();
}

foo.cpp

#include "Foo.h"

#include <GL/glu.h>

GLUtesselator *Foo::tess = gluNewTess(); // System call

Foo::Foo() {}
Foo::~Foo()
{
     // And of course I don't want to destruct it here,
     // because I'm going to use the tesselator in other instances of Foo
     // Otherwise:
     // gluDeleteTess(tess);
}

Are there any better alternatives to create a method to remove static material and call it when the application terminates?
Or I can say: “Oh, anyway, the application is terminated. The OS will free up memory ...”?

thank

+5
source share
4 answers

Simple Do not make a static element a pointer.
Then it will be properly built and destroyed.

foo.h

#include <GL/glu.h>

class Foo
{
    private:
        static GLUtesselator  tess;
    public:
                 Foo();
        virtual ~Foo();
};

foo.cpp

// 
GLUtesselator  Foo::tess;

gluNewTess() gluDeleteTess(), . , . shared_ptr .

foo.h

#include <GL/glu.h>

typedef std::shared_ptr<GLUtesselator,void (*)(GLUtesselator*)> AutoGluTess;
class Foo
{
    private:
        static AutoGluTess  tess;
    public:
                 Foo();
        virtual ~Foo();
};

foo.cpp

// 
AutoGluTess    Foo::tess(gluNewTess(), &gluDeleteTess);
+7

. , , , (: , ).

,

  • , ,
  • ( ), auto_ptr tr1::unique_ptr, , ( ).
+2

:

CFoo* pFoo= NULL;

void DoneFoo()
{
    delete pFoo;
}

void Init()
{
    pFoo= new CFoo();
    atexit(DoneFoo);
}

class CFoo
{
     ......
};

#define NewFoo(F_name)                                                             \
    CFoo* F_name##Init();                                                          \
    void  F_name##Done();                                                          \
    CFoo* F_name= F_name##Init();                                                  \
    CFoo* F_name##Init()  { CFoo* F= new CFoo(); atexit(F_name##Done); return F; } \
    void  F_name##Done()  { delete F_name; }    

NewFoo(F1);

:

class CFoo
{
    static int* pKuku;
    static void DoneKuku() { delete pKuku;                     }
    static int* InitKuku() { atexit(DoneKuku); return new int; }
public:
};

int* CFoo::pKuku= CFoo::InitKuku();

, , , . "" , "", .

+2

, . GLUtesselator , , - .

: ", , . ..."

+1
source

All Articles