S
Simon Elliott
I have a C++ file which needs to work along these lines:
class foo
{
private:
int i1_;
public:
foo():i1_(12){}
~foo()
{
ExecuteSomething(); // Must be executed before program exits
}
int GetI1(void)const{return(i1_);}
void SetI1(int i1){i1_ = i1;}
};
static foo MyStaticFoo;
extern void f1()
{
MyStaticFoo.SetI1(13);
}
extern int f2()
{
return(MyStaticFoo.GetI1());
}
In other words, it needs to retain some state in a static object. On
program exit, the static object's destructor must be called.
Unfortunately, it seems that foo's destructor is (sometimes) being
called before some of the functions which need to access it.
How can I change this design so that foo is not destroyed until I'm
finished with it?
I can't change
static foo MyStaticFoo;
to
static foo* MyStaticFoo = 0;
and use dynamic allocation, because then someone will have to remember
to call delete on the object, and if they forget, the destructor won't
be called.
I don't think I can use a singleton pattern either, because I still
can't guarantee that the object won't be destroyed while I still need
it.
Any thoughts?
class foo
{
private:
int i1_;
public:
foo():i1_(12){}
~foo()
{
ExecuteSomething(); // Must be executed before program exits
}
int GetI1(void)const{return(i1_);}
void SetI1(int i1){i1_ = i1;}
};
static foo MyStaticFoo;
extern void f1()
{
MyStaticFoo.SetI1(13);
}
extern int f2()
{
return(MyStaticFoo.GetI1());
}
In other words, it needs to retain some state in a static object. On
program exit, the static object's destructor must be called.
Unfortunately, it seems that foo's destructor is (sometimes) being
called before some of the functions which need to access it.
How can I change this design so that foo is not destroyed until I'm
finished with it?
I can't change
static foo MyStaticFoo;
to
static foo* MyStaticFoo = 0;
and use dynamic allocation, because then someone will have to remember
to call delete on the object, and if they forget, the destructor won't
be called.
I don't think I can use a singleton pattern either, because I still
can't guarantee that the object won't be destroyed while I still need
it.
Any thoughts?