When is a static function-scope object destroyed?

Hi all,
I'm trying to find some reference material for the destruction of a function-scope object.

I am able to find a lot of material about static class members, but not about this.

For context, I had a class similar to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Class MyFailingClass {
  public:
  void function();
  ...
  ~MyFailingClass();
}

void MyFailingClass::function() {
  static MutexClass mutex;
  mutex.lock();
    ...
  mutex.unlock();
}

MyFailingClass::~MyFailingClass() {
  function();
    ...
}


The class was also instantiated as a static function-scope object, and this was giving me issues with the mutex already being gone when function() was called by the class destructor. I changed the mutex to be a member of the class rather than as above (as I should have done to begin with) and all is well, but I want to understand a bit more about the order of destruction for these variables.

Thanks for any pointers or references,

Jivan
Last edited on
static function-scope objects are destroyed while main function returns

output of this code may help you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>

using namespace std;

class myClass
{
public:
	myClass()
	{
		cout <<"\nconstructing......\n";
	}
	~myClass()
	{
		cout <<"\ndesssssssssssstrrrrrrrrrrrcting......\n";
	}
};


void fun(void)
{
	cout <<"\nbefore static\n";
	static myClass ob;
	cout <<"\nafter static\n";
}

int main(int argc, char* argv[])
{
	cout <<"\nbefore fun()\n";
	fun();
	cout <<"\nafter fun()\n";
	cout <<"\nagain checking.........\n";
	cout <<"\nbefore fun()\n";
	fun();
	cout <<"\nafter fun()\n";

	return 0;
}
Last edited on
Hi surender,
Thanks for the reply. I understand that they are destroyed when the program exits, my question is on the order they are destroyed in if there is more than one. For example:
1
2
3
4
5
6
7
8
9
10
11
void fun(void)
{
	static myClass ob1;
}

void morefun(void)
{
	static myClass ob2;
	static myClass ob3;
}


Are there any specifications what order these (ob1, ob2, ob3) will be destroyed in?
I can write some code to check my compiler, but I'd like to know if there are any specifications or if it is compiler-dependent.
Last edited on
You shouldn't rely on static objects being destructed in any particular order, as it is unpredictable. Assume they're destructed at the same time.
Actually, this assumption is valid for anything that happens after main() returns.
Thanks helios
Topic archived. No new replies allowed.