Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is memory deallocated in relation to static variables? [duplicate]

Tags:

c++

I was wondering if someone could shed some light on the deallocation-of-memory processes in c++.

If I have a struct that I declare static, such that it's constructor is the first thing to execute and its destructor is the last thing to execute:

struct initializer execute_before_and_after_main {
     initializer() { init(); }
     ~initializer() { cleanup(); }
}
static initializer execute_around_main;

And I then have something like:

class my_class {
    my_object objects[100];
}
extern my_class gobal_my_class;
my_class global_my_class;

and main is not important here:

int main (int argc, char* argv[]) {
    ....
} 

When cleanup() is called, is the objects array now containing deallocated/invalid memory? Is there a standard sequence of initialisation/destruction that c++ implements here that someone could perhaps point me to?

Thanks

EDIT: I understand this type of code is possibly not the best practice, but I am still wondering if the behaviour is defined.

like image 563
ricky116 Avatar asked Oct 22 '22 03:10

ricky116


1 Answers

Static and global variables both have static storage duration meaning they are freed when the program ends. From reading one of the duplicates I found that if the code is all in the same translation unit (which yours is) then objects with static storage are destructed in the reverse order of construction. If the objects are in different translation units you can't guarantee anything.

When cleanup() is called, is the objects array now containing deallocated/invalid memory?

Yes but it doesn't really matter since it is only called once the object is out of scope

Is global_my_class destructed before execute_around_main?

yes, global my class is destructed first because it is initialized last

like image 153
aaronman Avatar answered Nov 15 '22 04:11

aaronman