Frage

I created a sub-class, B, for a class that I'll call A.

I wrote this code for work, so I'm going to generalize the actual code:

class A
{
public:
  A ()
     {
     important_variable = new Type();
     ...
     };

  ~A (void) { delete(important_variable); };      // Default destructor
  // more methods

protected:
  Type        *important_variable;
};

class B : public A
{
public:
B() : A() { important_variable = another_var; }
~B() {};

Type *another_var;
};

Having this code for B caused my program to crash with an 'Unhandled Exception'.

Now, when I change the code for class B to this:

class B : public A
{
public:
B() : A() { another_var = new Type(); important_variable = another_var; }
~B() {};

Type *another_var;
};

The exception goes away.

I think that my original code for B caused my program to crash because A was trying to delete a variable that was still being pointed to by another variable. Is this reasoning correct? Why does the new code for B cause my program to work?

War es hilfreich?

Lösung

There are many flaws in your code, but the one most likely to cause a crash is this line:

important_variable = another_var;

another_var does not point anywhere that can be deleted. But important_variable is made to point to the same place, and then is deleted in A's constructor.

Your "solution" masks the problem, at the cost of a memory leak. When you do this

another_var = new Type(); important_variable = another_var;

the original dynamically allocated Type object that important_variable pointed to is lost.

Besides that, you need to follow the rule of three.

Andere Tipps

new and delete are for handling heap allocations only. I suspect that in your first listing of class B, another_var is likely allocated on the stack and this is what is causing the exception in the destructor. Additionally, whenever you have a base class you really should make its destructor virtual.

The original version crashed because you set important_variable to uninitialised another_var and then you tried to delete this uninitialised value. In the "corrected" version you at least do not delete uninitialised variables, but still in contains memory leak - you assign newly allocated memory to important_variable and then immediately you assign to this variable the value of another_var, so the originally allocated memory is no longer accessible and will leak.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top