When a variable is reassigned, the destructor is not called:

Object foo = Object(a,b);
foo = Object(c,d);

so, the destructor will only be called at the end of the scope for Object(c,d), which can obviously cause problems. Now, in this specific case it doesn't bother me too much: it is enough to declare 2 different objects:

Object foo1 = Object(a,b);
Object foo2 = Object(c,d);

In this way the destructor of both objects will be called at the end.

However, there is a case when I necessarily need to reassign a variable, i.e. in an object constructor such as:

SuperObject(Point point1, Point point2) : delay_object_(DelayObject(0)) {
  double distance = distance(point1, point2);
  double delay = distance / speed;

  delay_object_ = DelayObject(delay);
}

In fact the DelayObject parameter is not easy to calculate (in this example I also omitted a few other passages), and I want to avoid doing it in the initialisation list.

I thought I can force the deletion by putting the object in the heap and explicitly calling the destructor:

SuperObject(Point point1, Point point2) : p_delay_object_(new DelayObject(0)) {
  double distance = distance(point1, point2);
  double delay = distance / speed;

  delete p_delay_object_;
  p_delay_object_ = new DelayObject(delay);
}

but this really looks ugly to me, as I prefer to use dynamic allocation only when strictly necessary. Am I missing something?

Cheers!

Edit
Report