Why is the destructor called in this code?

I am reading a Data Structures book on how to implement an ArrayList, and I have the following code for the erase function:

template <typename T>
void ArrayList<T>::erase(int index) {

    //Delete the element whose index is "index"
    //Throw illegalIndex exception if no such element 
    checkIndex(index);



    std::copy(dynArr+ index + 1, dynArr + listSize, dynArr + index);

    dynArr[--listSize].~T(); //invoke destructor


}

A destructor is defined as:

template<typename T>
ArrayList<T>::~ArrayList() {


delete [] dynArr;


}

I was a little confused about what exactly is happening there. Doesn't the destructor exist to remove the entire array when it needs to be deleted?

+3
source share
1 answer

The T destructor is called (and not the destructor ArrayList<T>), and this is probably because objects of type T created in a pre-allocated array and not individually on the heap using a specialplacement new operator

Therefore, when one is deleted, there is no need to release any memory, but you want to call the destructor so that the state is cleared.

. (, std::vector) . : void* operator new (std::size_t size, void* ptr) throw();

, , delete , , , . AFAIK, , dtor

, , , :

std:: copy :

template<class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
   while (first!=last) {
      *result = *first;
      ++result; ++first;
   }
   return result;
}

, = . + 1. , , . , , , .

. , , ++ 11 std:: copy (, boost::move)

2. location > index, .

+2

All Articles