Consider the following code snippet:
#include <vector>
using namespace std;
void sub(vector<int>& vec) {
vec.push_back(5);
}
int main() {
vector<int> vec(4,0);
sub(vec);
return 0;
}
Assuming "vec" has no space left to store the 5 in the "sub" function, where does it allocate new memory?
In the stack frame of the sub function? In that case the 5 would be deleted at the end of the sub function. But the stack frame of the main function can't grow, as the stack frame of the sub function lies on top of the stack at that moment.
Does a std::vector allocate memory for its elements on the heap?
But how does it free that heap memory?
If it's a local vector on the stack, the stack frame of a function including the vector is deleted in the end without signaling the vector that it will be deleted?