I know C, but I’m not good at C++.
The following code will crash (In getval(), using reference as a parameter is ok).
And value of *p is changed after first cout statement. It looks there is some overwriting caused by out of bound of memory.
My question is why it crashed (or why its value is changed).
It’s ‘call by value’ of object, so should it work anyway?
class myclass {
int *p;
public:
myclass(int i);
~myclass() { delete p; }
int getval(myclass o);
};
myclass::myclass(int i)
{
p = new int;
if (!p) {
cout << "Allocation error\n";
exit(1);
}
*p = i;
}
int myclass::getval(myclass o)
{
return *o.p;
}
int main()
{
myclass a(1), b(2);
cout << a.getval(a) << " " << a.getval(b) << endl;
cout << b.getval(a) << " " << b.getval(b) << endl;
return 0;
}
This is a very common problem of shallow copy and double delete. Compiler picks up the default copy constructor and both
a.pando.pare pointing to same memory location. When both objects invoke their destructor, thedelete p;statement is executed twice. Freeing the same memory multiple times is an undefined behavior and it results in crash in your system.If properly coded, then yes it would work. Make a deep copy of
p‘s content and then it should work. However, it’s better to pass by reference till it’s possible.