C++ 参数堆与堆栈

标签 c++ arguments parameter-passing heap-memory stack-memory

假设我创建了两个 vector ,一个在堆上,一个在栈上:

Vector<int> vector1;
Vector<int>* vector2 = new Vector<int>;

然后我通过 vector1分成两个函数,比如说,foo1(Vector<int>)foo2(Vector<int>&) .我也通过vector2进入foo3(Vector<int>*) .

由于我是 C++ 的新手,我对这里的行为差异感到很困惑。

  1. 我对 foo1 这样说对吗? , 整个 vector1被复制,对于 foo2 , 仅引用 vector1被传递到函数中?

  2. 但不是 vector1 ,在堆栈上声明,除了创建它的范围外,应该在其他任何地方(即从内部 foo2 )都无法访问?

  3. 另外,修改vector1的内容里面foo1 , foo2影响原始 vector ?

  4. 并且是 vector1在其范围结束时自动销毁,还是我们必须手动删除它?

最佳答案

Am I right to say that for foo1, the entire vector1 gets copied, and for foo2, only the reference to vector1 gets passed into the function?

正确。

But isn't vector1, declared on the stack, supposed to be inaccessible anywhere else (i.e. from inside foo2) except the scope in which it was created?

它只是 vector1名称,外部无法访问,但您可以自由地传递它的地址(通过引用或指针传递)。当然,只要函数不返回,它就会继续存在,因此返回指向它的指针将是错误的(因为它会指向一个不再存在的对象)。

这与堆上的分配不同,堆上的分配没有范围限制的生命周期或自动删除 - 它留给你。这是一把双刃剑:您可以拥有具有自定义生命周期的对象,但您必须记住在不再需要它们时确实删除它们。

Also, does modifying the contents of vector1 inside foo1, foo2 affect the original vector?

foo1 的参数是一个新的、分离的 vector ,对它所做的任何修改都将保留在函数的本地。 foo2 的参数引用 vector1,因此它会影响原始 vector (实际上,引用通常被描述为其他对象的“别名”)。

And is vector1 automatically destroyed at the end of its scope, or do we have to delete it manually?

它会像任何局部变量一样自动销毁。 但是:vector2 必须手动删除,因为本地对象只是指针,没有析构函数(默认情况下它没有t 拥有它指向的对象)。

关于C++ 参数堆与堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23607360/

相关文章:

c++ - 为什么 ZeroMQ 轮询会抛出错误 : "socket operation on non-socket"?

c++ - 从 C++ 中的文本文件中读取带有杂散空格的逗号分隔值

python - 使用未知数量的参数调用 python 函数

c++ - C++ 能做什么在任何其他语言中都太难或太乱了?

c++ - Golang 中的移位指令

r - 在嵌套函数中传递参数以更新默认参数

将可变数量的参数插入到字符串中的 Pythonic 操作

c# - 传递 IEnumerable<T> 时 T 重要吗?

Powershell:New-LocalUser - 找不到接受参数 'True' 的位置参数

r - 如何解决 `fun<-` 从评估 `value` 开始的事实?