C++ 一个不做任何事情的函数能改变一个对象吗?
为什么一个不做任何事情的函数会改变一个对象 我有以下代码:C++ 一个不做任何事情的函数能改变一个对象吗?,c++,pass-by-reference,pass-by-value,C++,Pass By Reference,Pass By Value,为什么一个不做任何事情的函数会改变一个对象 我有以下代码: void sample(SList a) { cout << "\nIn Function"; a.print(); } int main() { srand(500); int total = 10; SList llist; for(int i = 0; i < total; i++) { llist.add_head(rand() % 1
void sample(SList a)
{
cout << "\nIn Function";
a.print();
}
int main()
{
srand(500);
int total = 10;
SList llist;
for(int i = 0; i < total; i++)
{
llist.add_head(rand() % 100);
}
llist.print();
llist.print();
sample(llist);
llist.print();
return 0;
}
我的问题是,一个与SList无关的函数sample
,正在更改SList。它是怎么做到的?SList是一个单链接列表
我认为这与传递值有关。如果有人告诉我我无知地遗漏了什么,那就太好了
编辑:标题问题的答案是肯定的。请看答案。看
SList的
复制构造函数和析构函数。我猜测,在没有看到它们的情况下,复制构造函数生成数据的浅层副本,析构函数删除该数据。问题是在调用sample
时调用复制构造函数,然后在退出sample
时调用析构函数。有几种方法可以解决这个问题
您可以通过引用传递SList
。这将阻止调用复制构造函数和析构函数
您可以在复制构造函数中深度复制数据
另一个解决方案是让
SList
将其数据存储为共享\u ptr
而不是原始数据。是的!明白了。非常感谢。
70 69 14 3 18 71 70 17 57 98
70 69 14 3 18 71 70 17 57 98
In Function
70 69 14 3 18 71 70 17 57 98
0 34365728 34365696 34365664 34365632 34365600 34365568 34365536 34365504 34365472