【发布时间】:2011-10-19 08:01:23
【问题描述】:
我知道 C,但我不擅长 C++。
下面的代码会崩溃(在getval()中,使用引用作为参数是可以的)。
并且*p 的值在第一个cout 语句之后更改。看起来内存溢出导致了一些覆盖。
我的问题是它为什么会崩溃(或者为什么它的值会改变)。 它是对象的“按值调用”,所以它应该工作吗?
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;
}
【问题讨论】:
-
提示:当你的对象被复制并且两个副本都被破坏时会发生什么?
标签: c++ crash runtime-error pass-by-value