Reputation: 53317
I have an object that manages a global resource and has several ivars (kinda auto objects) that each access that resource. When I destory the object I close the resource in it's destructor. Unfortunately, the ivars also access that resource once in their d-tors. Since ivar d-tors are called at the end of the object d-tor this obviously crashes.
My question is now: is it possible (and how) to determine the order of destruction (probably more like: can I make the ivar have their d-tors called before my object's d-tor ends)?
I can probably convert all the value ivars to reference ivars and delete them explicitely, but this has serious consequences on other parts, so I'd like to gauge the options I have to stay with my current value types.
Code example:
class A {
A() { inc_ref_in_context(); }
~A() { dec_ref_in_context(); }
};
class Container {
A _ivar1;
A _ivar2;
A _ivar3;
...
~Container() { release_context(); }
}
Upvotes: 0
Views: 113
Reputation: 16761
Order of members initialization/destruction is also well defined, so as per aschepler's comment her's some code:
class A;
class B {
~B() { release_context(); }
};
class Container {
B context;
A _ivar1;
A _ivar2;
A _ivar3;
}
Upvotes: 1
Reputation: 2216
Why not have the resource be responsible for the ivars that access it? e.g. add a method "get_new_ivar()" which creates and tracks all the ivars.
Then, in the destructor of the resource you can destruct all the ivars.
Upvotes: 0
Reputation: 254431
It seems odd that the "context" is reference-counted, but doesn't release itself when the reference count reaches zero. That might be the most robust solution.
Otherwise, you could release it in the destructor of a base class, or an extra member declared before the "ivar" members.
Upvotes: 1