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?
map<string, list<int>> m;
contains lists, not references to lists. So your
m.insert({"ABC", list_to_insert});
will create a copy of the passed list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.