static variables and memory cleanup

A

Anonymous

I want to carry out initialisation ONCE for use by a class.

I am using a dummy static variable dummy to do this. However, during my
initialisation code, I am allocating memory etc for various variables
used by the class.

Although I am not explicitly deallocating memory, alloc'd memory will be
returned to the heap when the app terminates - but I am not happy with
this. I am looking for a way to explicitly deallocate memory when there
are no more instances of the class that requires the new'd variables.

I can think of several ways of doing this - all of which seem a bit of a
hack (or maybe even wrong?). i'd like some comments on my ideas, and
pointers if any of my proposed solns are wrong or have side effects - or
preferably, a better way of solving this problem.

1). Use a class variable for reference counting and explicitly
"uninitialize" when last instance is dying

2). Wrap up all of the variables to be new'd during the initialisation
process, into a data type (struct or class), make a class variable of
that type, initialize it once, and deallocate in the new data types
destructor

Any more ideas ?
 
C

Chris ( Val )

I want to carry out initialisation ONCE for use by a class.

I am using a dummy static variable dummy to do this. However, during my
initialisation code, I am allocating memory etc for various variables
used by the class.

Although I am not explicitly deallocating memory, alloc'd memory will be
returned to the heap when the app terminates - but I am not happy with
this. I am looking for a way to explicitly deallocate memory when there
are no more instances of the class that requires the new'd variables.

I can think of several ways of doing this - all of which seem a bit of a
hack (or maybe even wrong?). i'd like some comments on my ideas, and
pointers if any of my proposed solns are wrong or have side effects - or
preferably, a better way of solving this problem.

1). Use a class variable for reference counting and explicitly
"uninitialize" when last instance is dying

2). Wrap up all of the variables to be new'd during the initialisation
process, into a data type (struct or class), make a class variable of
that type, initialize it once, and deallocate in the new data types
destructor

Any more ideas ?

struct foo {
~foo() { std::cout << "Destructed\n"; }
};

int main()
{
foo* f = new foo();
f->~foo();

std::cin.get();
return 0;
}

Cheers,
Chris Val
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,206
Latest member
SybilSchil

Latest Threads

Top