user2282596
user2282596

Reputation: 57

How to use destructor with non pointer attribute

I am stuck on making use of my destructor My brief code structure is such that

class test
{
   private:
     string code;
     int digit, num_digit;  

   //destructor
   ~test() 
   {
      if(digit >= 0 && digit > num_digit)
      {
         for(unsigned int i=0; i<code.length(); i++) delete &code[i];
      }
   }
};

 <more code> .............
 <more code> .............

 int main()
 {
      Test test1
      test1.~test();
 }

My core get aborted when going through the part for destructor. Unix complier says Aborted - 'core dumped' Any idea for it?

Upvotes: 3

Views: 3125

Answers (2)

hmjd
hmjd

Reputation: 121971

The abort is occurring because an attempt is being made to delete an object that was not dynamically allocated: only delete what was created vianew (and delete[] for new[]). The code member is not dynamically allocated. It will be destroyed automatically when the containing object is destroyed. In the case of Test there is no reason to hand code a destructor.

This is incorrect:

test1.~test();

Don't explicitly invoke the destructor of an object. The destructor will be invoked automatically when test1 goes out of scope. For dynamically allocated objects the destructor will be invoked when it is deleted.

Upvotes: 7

parkydr
parkydr

Reputation: 7784

You can only delete pointers created with a call to new.

You are deleting a pointer to string which is on the stack. This gives you the core dump.

Upvotes: 3

Related Questions