附加到具有非动态分配堆栈的向量

时间:2021-02-22 21:18:18

I'm working on a coding question, and to solve it I'm creating my own data structure (class), "SetOfStacks", that has as a member a vector of stacks. In one of the member functions of SetOfStacks, I need to expand the vector using the push_back() function. To do this, I declare a stack variable (non-dynamically) in the member function and then pass that variable in to push_back().
The code works fine, but I don't understand why. I would figure that after the member function has finished executing, the stack variable would go out of scope (because it is not dynamically allocated) and as a result the vector would contain garbage. I would think that the solution would be to use dynamically allocated memory. Why does this work? My best hypothesis is that push_back() takes in the new stack by value and not by reference, effectively making a new copy of it. Any help is appreciated!

我正在编写一个编码问题,为了解决这个问题,我正在创建自己的数据结构(类),“SetOfStacks”,它具有堆栈向量的成员。在SetOfStacks的一个成员函数中,我需要使用push_back()函数展开向量。为此,我在成员函数中声明一个堆栈变量(非动态),然后将该变量传递给push_back()。代码工作正常,但我不明白为什么。我想在成员函数执行完毕后,堆栈变量将超出范围(因为它没有动态分配),因此向量将包含垃圾。我认为解决方案是使用动态分配的内存。为什么这样做?我最好的假设是push_back()按值而不是通过引用接收新堆栈,从而有效地创建它的新副本。任何帮助表示赞赏!

1 个解决方案

#1


1  

When you push_back() the stack elements to the vector, the element is passed by value to the vector, and not as a reference, so even if after the function definition the stack elements got destroyed, the vector has got the value already.

当你将堆栈元素push_back()传递给向量时,元素会通过值传递给向量,而不是作为引用,因此即使在函数定义之后堆栈元素被破坏,向量也已经获得了值。

This you can related with the return value from function to caller. Even if the return value is local to function stack( i.e it is going to be destroyed after function gets executed), the return values gets copied to caller function before it gets destroyed.

这可以与函数到调用者的返回值相关联。即使返回值是函数堆栈的本地值(即在函数执行后它将被销毁),返回值也会在被销毁之前复制到调用函数。

#1


1  

When you push_back() the stack elements to the vector, the element is passed by value to the vector, and not as a reference, so even if after the function definition the stack elements got destroyed, the vector has got the value already.

当你将堆栈元素push_back()传递给向量时,元素会通过值传递给向量,而不是作为引用,因此即使在函数定义之后堆栈元素被破坏,向量也已经获得了值。

This you can related with the return value from function to caller. Even if the return value is local to function stack( i.e it is going to be destroyed after function gets executed), the return values gets copied to caller function before it gets destroyed.

这可以与函数到调用者的返回值相关联。即使返回值是函数堆栈的本地值(即在函数执行后它将被销毁),返回值也会在被销毁之前复制到调用函数。