Hey;

I'm practicing with template classes. When I declare a user-typed destructor for this template class, the program freezes and needs to be closed explicitly.

Obviously, in the destructor, I am trying to release the memory allocated to hold the coordinates[3] array. What is the problem with declaring a user-typed destructor?

#ifndef POINT_H
#define POINT_H

template<class T>
class Point
{
    typedef T value_t;

public:
    Point(){}
    Point(T coor[])
    {
        coordinates[0] = coor[0];
        coordinates[1] = coor[1];
        coordinates[2] = coor[2];
    }
    Point(const Point& p)
    {
        coordinates[0] = p.coordinates[0];
        coordinates[1] = p.coordinates[1];
        coordinates[2] = p.coordinates[2];
    }

    ~Point() //The problem occurs here...
    {
        delete[] coordinates;
    }
private:
    value_t coordinates[3];
};
#endif

code:

#include <iostream>
#include "Point.h"

using namespace std;

int main()
{
    double arg[3] = {0,1,2};
    Point<double> myPoint(arg);
    myPoint.~Point();
    return 0;
}

Edited 3 Years Ago by mike_2000_17: Fixed formatting

The problem has nothing to do with either templates or destructors. This too will result in undefined behaviour:

int main()
{
    int coordinates[3] ;
    delete[] coordinates ; // ???
}

Well, you should not delete what you have not created :)

delete is is for objects created on the heap with new. So simply remove the delete statement.

Thanks guys. I thought since it is a member of the class, it will be placed on the heap.

This question has already been answered. Start a new discussion instead.