I've got some problems whith the overload of operator=. My code is
#include <stdlib.h>
#include <iostream>
const std::size_t DIM = 10;
template <typename T>
class rowvec
{
private:
T* m_pnt;
std::size_t m_dim;
public:
rowvec();
rowvec(std::size_t);
~rowvec();
rowvec<T>& operator=(const rowvec<T>& x);
T* pnt();
};
template <typename T>
rowvec<T>::rowvec()
{
m_dim = DIM;
m_pnt = (T*) calloc (DIM ,sizeof(T));
}
template <typename T>
rowvec<T>::rowvec(std::size_t n)
{
m_dim = n;
m_pnt = (T*) calloc(m_dim,sizeof(T));
}
template <typename T>
rowvec<T>::~rowvec()
{free(m_pnt);}
template <typename T>
rowvec<T>& rowvec<T>::operator=(const rowvec<T> &x)
{
std::cout << "hello" << std::endl;
if (this != &x)
{
free (m_pnt);
this->m_dim=x.m_dim;
m_pnt = (T*) calloc (m_dim,sizeof(T));
for (int i=0; i!=m_dim; i++)
*(m_pnt+i)=*(x.m_pnt+i);
}
return *this;
}
template <typename T>
T* rowvec<T>::pnt()
{return m_pnt;}
int main()
{
rowvec<int> k(3);
rowvec<int> c=k;
std::cout << "ok" << std::endl;
return 0;
}
There are no compiling error, but when I run the result is:
ok
*** Error in `./blog': double free or corruption (fasttop): 0x0000000001a5e010 ***
If I change code in this way:
int main()
{
rowvec<int> k(3);
rowvec<int> c;
c=k;
std::cout << "ok" << std::endl;
return 0;
}
everything is ok (output is)
hello
hello
ok
Is there a way to allow a declaretion like "rowvec c=k;" ?