user2131014
user2131014

Reputation: 1

Delete p execution in destructor

I do have doubt regarding use of delete p. In most of the scenarios we call delete inside the destructor if we would have called something int *p = new int (10); but as per below code snippet (original code of delete p) it already invoke the destructor then call the operator delete then why we should call delete p inside the destructor.

Original code:

delete a;
if (a != NULL) {
  a->~A();
  operator delete(a);
}

code snippet where we call the delete a inside destructor

class B
{
  int *a;
  public:
  B()
  {
    a=new int(90);
  }
  ~B()
  {
    cout<<"B's destructor";
    delete a;
  }
  void dial()
  {
    cout<<"dial the tone";
  }
}

Upvotes: 0

Views: 103

Answers (3)

Saurabh B
Saurabh B

Reputation: 165

At all the places where new allocates the memory dynamically then we need to use operator delete to free the memory.Please check the description in the below mentioned link. http://en.cppreference.com/w/cpp/memory/new/operator_delete

Upvotes: 0

Olaf Dietsche
Olaf Dietsche

Reputation: 74108

Don't do that! This is a double destroy and a double free

delete a;             // calls destructor and then frees the memory
if (a != NULL) {
  a->~A();            // calls destructor again
  operator delete(a); // frees memory again
}

This one is ok, because you allocated the memory in the constructor

~B()
{
    cout<<"B's destructor";
    delete a;
}

With , you can use std::unique_ptr instead

class B
{
    std::unique_ptr<int> a;
public:
    B() : a(new int(90));
    {
    }
    ~B()
    {
        cout<<"B's destructor";
        // std::unique_ptr will take care of memory
        // no delete a neccessary
    }
    ...
};

Upvotes: 1

ForEveR
ForEveR

Reputation: 55897

Function operator delete and delete expression are not same. Defaulted operator delete only freed memory, but expression calls destructor, before freeing memory. Read http://en.cppreference.com/w/cpp/language/delete

delete a;
if (a != NULL) {
  a->~A();
  operator delete(a);
}

Very-very strange snippet. There is UB here.

Upvotes: 0

Related Questions