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;
}

Recommended Answers

All 3 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.