Thursday, March 21, 2019

c++ - Why is the destructor called multiple times when a class object containing a pointer member is passed by reference? How do I correct this?

I have a class of the form



class A
{
int **a;
//other members
}



In some function, I pass an object of class A, say, obj, by reference



void func(A &o); //function declaration


and



func(std::ref(obj)); //function call



However, I got the following error - double free or corruption (!prev)



According to the linked question, this is because the destructor is called multiple times for the pointer member, a consequence of the copy constructor being called multiple times when copying, causing an attempted deallocation of memory already deallocated. However, as I am passing the complete object by reference, why should this happen? Shouldn't the address of the whole object be simply copied?



Suggestions for implementing a copy constructor in the form given in the above link and here won't help as they involve allocating a fresh amount of memory whenever the object is copied, whereas I would like to pass the object, and as a result the pointer member, by reference.



I looked at this and this, potential duplicates,but they didn't solve my problem.




Based on a few other answers, I also tried implementing a destructor as



~A()
{
delete[] a;
}


or




~A()
{
if(a)
{
delete[] a;
}
}


but neither solved the problem.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...