question about template class
I met a error when running the program. The error is
*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0000000000c19050 ***
|
the code is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#include <cassert>
#include <iostream>
using namespace std;
template<typename T>
class Vector {
T * data;
int sz;
public:
Vector() : data(NULL),sz(0) {
}
Vector(int s) {
data = new T[s]();
sz = s;
}
~Vector() {
if(data) delete[] data;
}
template<typename N> Vector(const Vector<N> & t) {
int * tmp = new T[sz]();
for(int i = 0 ; i < sz ; i++) tmp[sz] = t.data[i];
if(data) delete[] data;
data = tmp;
}
T & operator()(int i) {
assert(0 <= i && i < sz);
return data[i];
}
template<typename N> Vector<T> & operator=(const Vector<N> & t) {
int * tmp = new T[sz]();
for(int i = 0 ; i < sz ; i++) tmp[sz] = t.data[i];
delete[] data;
data = tmp;
return *this;
}
template<typename T1,typename T2> friend Vector<T1> f(const Vector<T1> & a,const Vector<T2> & b);
};
template<typename T1,typename T2>
Vector<T1> f(const Vector<T1> & a,const Vector<T2> & b) {
assert(a.sz == b.sz);
Vector<T1> retVal(a.sz);
for(int i = 0 ; i < a.sz ; i++) retVal.data[i] = a.data[i] + b.data[i];
return retVal;
}
int main()
{
Vector<int> t1(3),t2(3),t3;
for(int i = 0 ; i < 3 ; i++) {
t1(i) = i; t2(i) = i;
}
t3 = f(t1,t2);
return 0;
}
|
How does the double free happen? Thanks
You need a copy constructor. You do know that if you don't create one, the default will be used, right?
1 2 3 4 5 6 7
|
Vector(const Vector<T> &t) :
data(new T[t.sz]),
sz(t.sz)
{
for (int i = 0; i < sz; ++i)
data[sz] = t.data[i];
}
|
He does have one
1 2 3 4 5 6
|
template<typename N> Vector(const Vector<N> & t) {
int * tmp = new T[sz](); //sz has garbage
for(int i = 0 ; i < sz ; i++) tmp[sz] = t.data[i];
if(data) delete[] data; //data has garbage
data = tmp;
}
|
No he doesn't. That isn't a substitute for the correct one.
¿So I need to create the specific constructor, that would do the exact same thing as the templatized one? (once the errors are fixed)
Damn.
1 2
|
for (int i = 0; i < sz; ++i)
data[sz] = t.data[i]; //out of bounds
|
Yes that copy is incorrect, I missed that.
That templated thing doesn't initialise sz
either.
Topic archived. No new replies allowed.