Question

If i comment the line arr = 0; in destructor definition, the program terminates with an error. If i uncomment that line i.e., arr is set to 0, then the program executes without any error. Why is it so as there is no need of setting a pointer to NULL. The pointer itself is destroyed after the execution of destructor.

Screenshot of the error

Below is my code.

Array.h

#ifndef ARRAY_H
#define ARRAY_H
class Array
{
    int* arr;
    int size;
public:
    Array(int size = 10);
    Array(const Array& arr);
    ~Array();
    void display () const;
};
#endif

Array.cpp

#include "Array.h"
#include <iostream>
using namespace std;

Array::Array(int size)
{
    arr = new int[size];
    this->size = size;
    for (int i = 0; i < size; i++)
        arr[i] = i;
}

Array::Array(const Array& a)
{
    arr = new int[a.size];
    for (int i = 0; i < a.size; i++)
        arr[i] = a.arr[i];
    size = a.size;
}

Array::~Array()
{
    delete[] arr;
    arr = 0;
}

void Array::display() const
{
    cout << endl;
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}

Main.cpp

#include <iostream>
#include "Array.h"
using namespace std;

int main()
{
    Array arr(4);
    Array a1 = arr;
    a1.display();
    arr.~Array();
    a1.display();

    return 0;
}
Was it helpful?

Solution

You shouldn't be calling the destructor here:

arr.~Array();

When arr goes out of scope, the destructor is called a second time. That leads to undefined behaviour when delete[] is called on the pointer data member arr. When you set that to 0, you side-step the problem, but the fact remains that you shouldn't be invoking the destructor like that.

Here's an example showing how the lifetime of an automatic storage object is bound to its scope:

#include <iostream>

struct Foo
{
  ~Foo() { std::cout << "Foo destructor\n";
};

int main()
{
  std::cout << in main()\n";

  {
    Foo f;
  }  // f gets destroyed here

  std::cout << "Exiting main()\n";
};

OTHER TIPS

You don't need to explicitly call destructors. They will execute once the program terminates. http://www.learncpp.com/cpp-tutorial/86-destructors/ look at the article under the heading constructor and destructor timing

The destructors are written to deallocate the memory assigned to pointers. Otherwise the pointer is deleted but its memory remains dangling. When the program terminates, all the variables will be lost from the memory, all resources will be deallocated, and during that time the destructor will execute itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top