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
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.
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.
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);
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
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).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With