3

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?

user2282596
  • 57
  • 1
  • 8
  • 2
    Why are you calling `test1.~test();` manually? You should never do that! – Alex Chamberlain Apr 26 '13 at 08:39
  • Also in your case your destructor is not only superfluos but causes undefined behaviour – Martin Drozdik Apr 26 '13 at 08:40
  • @AlexChamberlain actually there is one rare exception, that is when you use placement new. – Martin Drozdik Apr 26 '13 at 08:42
  • 3
    You seem to seriously misunderstand how constructors, destructors and dynamic allocation work in C++. Destructors are called *automatically* when an object's lifetime ends (local var goes out of scope, `new`ed object is `delete`d). You *must not* call them manually. And only call `delete` on something you allocated with `new`. For `std::string`, it's the job of its destructor to clean up the string. And it will do it. You might want to read a [good C++ book](http://stackoverflow.com/q/388242/1782465). – Angew is no longer proud of SO Apr 26 '13 at 08:43
  • 3
    @MartinDrozdik Sure. But that's very advanced, and for a beginner, just confusing. – Angew is no longer proud of SO Apr 26 '13 at 08:44
  • Totally.. Im not trying to use it thx – user2282596 Apr 26 '13 at 08:49

2 Answers2

7

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.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • 1
    @user2282596, internally `std::string` will have a dynmically allocated buffer but the `std::string` instance manges it itself. – hmjd Apr 26 '13 at 08:38
  • Could he not just do a dummy `test1 = Test();`? This will call the destructor on test1. – iago-lito Aug 29 '15 at 13:32
3

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.

parkydr
  • 7,596
  • 3
  • 32
  • 42