change your line
Code:
buffer = new char[strlen(p)];
with
Code:
buffer = new char[strlen(p)+1];
to make room for null character.
Now observe this
Code:
#include <iostream>
#include <cstring>
using namespace std;
template <typename T> class cls1
{
protected:
T* Arr;
public:
cls1(T arg)
{cout<<"Construct cls1"<<endl;
Arr = new T[1];
Arr[0] = arg;
}
~cls1() {delete [] Arr; cout<<"Destruct cls1"<<endl;}
};
class cls2
{
protected:
char *buffer;
public:
cls2() {}
cls2(char *p)
{
buffer = new char[strlen(p)+1];
strcpy(buffer, p);
cout<<"Constr. cls2"<<endl;
}
~cls2() {delete[] buffer; cout<<"Destruct cls2"<<endl;}
cls2(const cls2&){cout<<"Copy constr cls2"<<endl;}
};
template <class T>
class test
{
T x;
public: test()
{
cout<<"Constr. cls2"<<endl;
}
~test(){
cout<<"Destruct cls2"<<endl;
}
};
int main()
{
cls2 obj("amidja");
cls1<cls2> arr(obj);
cout<<"End of program!"<<endl;
}
And here's my output:
Constr. cls2
Copy constr cls2
Construct cls1
Destruct cls2
End of program
Destruct cls2
Destruct cls1
Destruct cls2
I think your problem is because you didn't define copy constructor and because of that same memory is deleted more times and this produce crash.
But there is a little mistery for me, and I hope someone with more experience will help.
First line:
Code:
cls2 obj("amidja");
will produce call of cls2 constructor.
Second line
Code:
cls1<cls2> arr(obj);
will produce copy constructor cls2 (expected), cls1 cnstructor (expected) and cls2 destructor(probably because of end of constructor cls1 - arg is going out of scope)
and at the end of program destructors are called cls2 cls1 and cls2 . I know how to explain cls1 and cls2, and know object that was created by copy constructor needs to be destroyed. But for me there is one destructor cls2 that I cannot explain (maybe it is the one before "end of program", maybe after)
Let try to solve this together.
- Micko