Elpezmuerto
Elpezmuerto

Reputation: 5571

Destructor for pointer to fixed size array

Suppose I have a C++ class with two private variables. A fixed size array, data, and a pointer to that array, pnt.

class MyClass
{
   private:
      double *pnt;
      double data[2];
   public:
      myClass();
      virtual ~MyClass();
      double* getPnt() const;
      void setPnt(double* input);
};

MyClass::MyClass()
{

   double * input;
   data[0] = 1;
   data[1] = 2;

   input= data;
   setPnt(input);
}

MyClass::~MyClass()
{
 delete this->pnt; // This throws a runtime error
}


void MyClass::setPnt(double * input)
{
   pnt = input;
}

double * MyClass::getPnt() const;
{
   return pnt;
}

int main()
{
   MyClass spam; // Construct object
   delete spam; // Error C2440: 'delete' cannot convert from 'MyClass' to 'void*'
}

There are two problems with this code. First if I try to call delete on the object, I get:

Error C2440: 'delete' cannot convert from 'MyClass' to 'void*'

Secondly, if I comment out the delete statement, I get a realtime error stating a debug assertion failed! and this:

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

My question is then: For a class with a pointer to a private fixed size array, how do I properly free memory, write/call the destructor?

P.S I can't use vector or nice containers like that (hence this question).

Upvotes: 1

Views: 4643

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283634

data is a subobject, it will be deallocated when the MyClass instance goes away. The compiler will insert any necessary code into the MyClass destructor to call destructors for all subobjects before the memory is freed.

Upvotes: 2

sehe
sehe

Reputation: 392931

I see no static array. I see a fixed-size array. Also memory for data is allocated as part of the object.

You must not explicitely delete a member of the class: the delete operator will take care of that IFF the instance was dynamically allocated.

 {
      MyClass x; // auto variable
 } // x destructor run, no delete operator

vs.

 {
      MyClass* x = new MyClass(); // heap allocation variable
      delete x; // x destructor run, ::delete de-allocates from heap
 } 

Upvotes: 5

Related Questions