Question

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(); }
}
Was it helpful?

Solution

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.

OTHER TIPS

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;
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top