how to wrtie destructor for class including a Unio

2019-04-29 15:28发布

问题:

I have a class contain different type of variables like this.

class Field
{
  union DATATYPE
  {
    int intValue;
    double doubleValue;
    char* charValue;
    MyClass* MyClassValue;
  } Value;
  ~Field()
  {
    delete[] Value.charValue;
    delete Value.MyClassValue;
  }
}

This destructor gives error. Since some objects don't have charValue initialized, the attempting to delete it raised error.