Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Best way to destruct static stuff

When I have a class containing static stuff, how can I free the memory at the end of the application 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 better alternatives to making a method to remove static stuff and call it when the app terminates?
Or can I say: "Oh, whatever, the application is terminated. The OS will free the memory..." ?

Thanks

like image 851
Martijn Courteaux Avatar asked Aug 28 '10 07:08

Martijn Courteaux


People also ask

How do you destroy a static object in C++?

Static objects are declared with the keyword static. They are initialized only once and stored in the static storage area. The static objects are only destroyed when the program terminates i.e. they live until program termination.

Can we delete static pointer in C++?

The answer to that question in C++ is no. The closest C++ has is typeid() / std::type_info , which is an object describing a type.


2 Answers

Simple. Don't make the static member a pointer.
Then it will be correctly constructed and destructed.

Foo.h

#include <GL/glu.h>

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

Foo.cpp

// 
GLUtesselator  Foo::tess;

If you have to use the gluNewTess() and gluDeleteTess() then you can use a shared pointer. I don't have a compiler so the exact usage may not be absolutely correct. But the shared_ptr does have this ability.

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);
like image 165
Martin York Avatar answered Oct 23 '22 22:10

Martin York


You don't need to destroy it. All operating systems I know will correctly free the memory and release any resources held by the object on application termination (Note: the destructor will not be called automatically, but the resources will be freed).

If you really want to destroy it though, either

  1. Don't use a pointer as Martin York describes,
  2. Or (if you need a pointer), use an auto_ptr or tr1::unique_ptr so that the pointee is automatically deleted when it goes out of scope (which is at the end of the application for static variables).
like image 25
Peter Alexander Avatar answered Oct 23 '22 22:10

Peter Alexander