一个对象具有一个动态数组作为实例变量。对象通过变量传递给函数-由于某种原因,即使方法未显式篡改对象,这也会更改动态数组中的数据。为什么会发生这种现象?
#include <iostream>
#include <string>
class A
{
public:
std::string * items;
A();
~A();
};
A::A()
{
items = new std::string[5];
for (int i=0;i<5;i++)
{
items[i] = "000000000000000000000000000";
}
}
A::~A()
{
if (items)
{
delete[] items;
}
}
void nothing(A a) //for some reason this method changes the object
{
std::cout<<"do nothing"<<std::endl;
}
int main()
{
A a = A();
nothing(a);
std::cout<<std::endl;//break
for (int i=0;i<5;i++)
{
std::cout<<a.items[i]<<std::endl; //this should cleanly print all 0's
}
return 0;
}
这将输出到屏幕:
什么都不做
P��oU0000000000000000000
oU0000000000000000000
oU0000000000000000000
oU0000000000000000000
0000000000000000000
但是当我将void nothing(A a)
更改为void nothing(A& a)
时,结果是
什么都不做
000000000000000000000000000
000000000000000000000000000
000000000000000000000000000
000000000000000000000000000
000000000000000000000000000
这是我期望的结果。损坏的数据来自哪里?那我的变更解决了什么问题?