Reputation: 57
I got two global variable:
static mutex m;
static object o;
and the destruct |o| need to use |n|
~object() {
auto_lock(&m);
}
but, I found that some times the |m| has been destructed. I wonder the order of global variable destruct?
Upvotes: 2
Views: 1730
Reputation: 49976
Destructors are always called in reverse order of construction. But if both variables are located in different compilation units then its hard to tell which will get constructed first. But if your variables are located in single compilation unit then you should be safe.
References: https://en.cppreference.com/w/cpp/language/destructor https://isocpp.org/wiki/faq/ctors#static-init-order
Upvotes: 4
Reputation: 27365
This problem can be solved through dependency injection (i.e. declare the mutex as the first thing in main and pass it to the constructor of object).
Upvotes: 0
Reputation: 2107
You can use reference count and self destruction approach - create m
and o
on heap and wrap them into some kind of reference counting and destruction container. So, when you create o
you should increment reference count on m
, and when you destruct o
you should decrement reference count on m
. Thus, you can control the order of construction/destruction of your global variables. Hope this helps.
Upvotes: 0
Reputation: 6632
Static objects are destructed in reverse order of construction BUT there's is very difficult (and almost impossible) to control that order.
If you need more control you may want to wrap them inside some structure.
struct EnsureOrder {
mutex m;
object o;
};
static EnsureOrder wrapper;
If those two objects are in the same .cpp
file I'm pretty sure the object should be constructed in the order they were defined.
Upvotes: 0