I'm new to C++ and trying to understand a simple example of inserting a list of integers into a map.
#include <iostream>
#include <map>
#include <list>
using namespace std;
map<string, list<int>> m;
void insert(list<int>& list_to_insert)
{
m.insert({"ABC", list_to_insert});
}
void setup()
{
std::list<int> local_list = { 7, 5, 16, 8 };
insert(local_list);
}
int main()
{
setup();
cout << m["ABC"].size(); // PRINTS 4
}
As far as my understanding, local_list
is a variable only known to the setup function. When I pass in a reference to the insert
function, I expect it to work. However, at the end of setup, I expect local_list to be removed from the stack frame. However, in my main function, when I call size()
, I see that it has in fact persisted throughout. I am not sure I understand how local_list
gets persisted at the end of setup()
. What is exactly happening here?