What do you need to do to clean up an int or char (not a pointer)?
Is it necessary to clean up this type of data after use?
sample ex:
// MAX = 100 ;
class Simple {
int a[ MAX ] ;
public :
~Simple ( ) ;
... // some declaration to fill, initialize ...
};
Is it essential to clean up data on the st开发者_如何学Pythonack, e.g. the array a[ MAX ]
in the example?
You don't have to overwrite int
or char
arrays unless you really care that data store in them can be somehow used to obtain sensitive data like passwords from your program.
See this and this questions for details on when that is needed. You likely don't need to worry about that.
But don't confuse overwriting memory with allocating memory. If you used new
to allocate an instance of your class Simple
be sure to use delete
to deallocate the instance at some moment, otherwise you have a memory leak.
You only need to clean-up what you allocated with new or new[] (or equivalent functions like malloc). Objects allocated on the stack are automatically destroyed on function return (this implies calling destructors on each class)
An automatic variable (a
in your example) expires after the block of code which it is contained ends. If that is what you mean
void foo()
{
int x;
char z;
int * y = new int(5);
...
return;
}
x
and z
do not exist any more after foo()
is over.
but what y
points too still exists, unless you delete y
, and if you don't a memory leak will occur
There is no particular cleanup required for int or char data. The compiler arranges for local variables to be placed on a temporary stack where the memory is reserved for their use while the function or block that declares them is in scope, after which their values are left there and may be overwritten by later uses of that memory. int and char data on the heap - from new
or malloc
- may be deallocated using delete
or free
, but again the old content is just left in memory until some further new
or malloc
reuses that memory. static variables exist throughout the runtime of the program. When a program terminates, the memory is released to the operating system and may be cleared back to some predictable state before another program is allowed to read it - the reason is for security: it prevents any data from the closed application being visible to another application and/or user.
In your code, nothing needs to be done to the class's int array by the destructor.
As others have pointed out, normally only what has been allocated with new
or malloc
needs to be cleaned up (released) explicitly.
I'll just add one little niggling detail: if your a[]
array should contain integers representing handles to resources (such as old-style Windows GDI handles, for instance) which you don't release elsewhere, your application will misbehave and eventually crash.
精彩评论