假设我创建了两个 vector ,一个在堆上,一个在栈上:
Vector<int> vector1;
Vector<int>* vector2 = new Vector<int>;
然后我通过 vector1
分成两个函数,比如说,foo1(Vector<int>)
和 foo2(Vector<int>&)
.我也通过vector2
进入foo3(Vector<int>*)
.
由于我是 C++ 的新手,我对这里的行为差异感到很困惑。
我对
foo1
这样说对吗? , 整个vector1
被复制,对于foo2
, 仅引用vector1
被传递到函数中?但不是
vector1
,在堆栈上声明,除了创建它的范围外,应该在其他任何地方(即从内部foo2
)都无法访问?另外,修改
vector1
的内容里面foo1
,foo2
影响原始 vector ?- 并且是
vector1
在其范围结束时自动销毁,还是我们必须手动删除它?
最佳答案
Am I right to say that for
foo1
, the entirevector1
gets copied, and forfoo2
, only the reference tovector1
gets passed into the function?
正确。
But isn't
vector1
, declared on the stack, supposed to be inaccessible anywhere else (i.e. from insidefoo2
) except the scope in which it was created?
它只是 vector1
的名称,外部无法访问,但您可以自由地传递它的地址(通过引用或指针传递)。当然,只要函数不返回,它就会继续存在,因此返回指向它的指针将是错误的(因为它会指向一个不再存在的对象)。
这与堆上的分配不同,堆上的分配没有范围限制的生命周期或自动删除 - 它留给你。这是一把双刃剑:您可以拥有具有自定义生命周期的对象,但您必须记住在不再需要它们时确实删除
它们。
Also, does modifying the contents of
vector1
insidefoo1
,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/