-1
#include "test.h"
template<typename T>
test<T>::test(const T &elem):data(elem)
{
}

template<typename T>
test<T>::~test()
{
    delete data;
}
template<typename T>
class test
{
private:
    T data;
public:
    test(const T &elem);
    ~test();
};
#include"test.h"
int main()
{
    test<int> a(2);
}

Classes and implementations and main functions are written in different files by me, when i try to compile it ,The compiler will report an error,but i can't find what's wrong.

Slava
  • 43,454
  • 1
  • 47
  • 90

2 Answers2

2

Your destructor as written:

template<typename T>
test<T>::~test()
{
    delete data;
}

assumes that data is a pointer. As it is declared having type T this means you cannot instantiate it with type int probably int * is the closest, but then your constructor does not make much sense. You probably want to remove delete statement from destructor, but it is difficult to say without seeing the whole picture.

Slava
  • 43,454
  • 1
  • 47
  • 90
0

If you wish to use the delete call in your destructor, your class member should almost always be type T*. However, having a member of type T is based on your use-case, and if you do, that member has memory allocated based on how you instantiate your class (calling new() and having it on the heap, or on the stack as you have). In this scenario, deleting the member T also happens when you call delete() on your instantiated class object, or is removed automatically from the stack when your object goes out of scope.