Sunday 6 January 2019

pointers - c++ overloading: overload of operator =




I've got some problems whith the overload of operator=.
My code is



#include 
#include


const std::size_t DIM = 10;



template

class rowvec
{
private:
T* m_pnt;
std::size_t m_dim;

public:

rowvec();
rowvec(std::size_t);
~rowvec();

rowvec& operator=(const rowvec& x);

T* pnt();
};



template
rowvec::rowvec()
{
m_dim = DIM;
m_pnt = (T*) calloc (DIM ,sizeof(T));
}


template
rowvec::rowvec(std::size_t n)

{
m_dim = n;
m_pnt = (T*) calloc(m_dim,sizeof(T));
}


template
rowvec::~rowvec()
{free(m_pnt);}



template
rowvec& rowvec::operator=(const rowvec &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
T* rowvec::pnt()
{return m_pnt;}





int main()
{
rowvec k(3);

rowvec 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 k(3);

rowvec 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;" ?


Answer



Even though there's a = in it, rowvec c=k; is copy-initialization and uses the copy constructor rather than the copy assignment operator.



Since your class doesn't define one, the default one which simply performs memberwise copy is used. That will only copy the pointer, which later causes the double free since both c and k's destructors will call free() on the same pointer.




Give your class a proper copy constructor (making a deep copy) and the double delete should go away.



Also, you are using C++. Don't use calloc/free. Use new and delete.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...