I'm a bit rusty on C/C++ and need some clarification on map and list scope. If I create a statically allocated map where the value is a statically allocated list, what happens when I pass this map to a function? For example, if I have `std::map<int, std::list> myMap;`, and I:
1. create the map
2. pass it to a function by reference
3. insert a key-value pair into the map within the function
4. then return from the function,
will my list still be usable afterward? I've heard conflicting things about local versus static allocations, and I want to make sure I'm clear on this. Thanks in advance!
3 Answers
You're on the right track! When you do something like `myMap[123] = x;` (where `x` is a list), it creates a new copy stored in the map. The lifespan of this new copy is controlled by the map itself. Just make sure whatever you're inserting is a value and not a reference to a temporary value, and you won't run into any issues.
Just a heads up, the term `static` relates more to your symbols' visibility across translation units. If it's declared within a function, it retains its value across calls, but if it's local, it disappears once you leave the function scope. So, keep that in mind when you're working with your variables and the scope of where they're declared.
If you pass the map into the function by mutable reference, it's the same as calling `insert()` right there in your main code. The data will persist, even when you return from the function, because the map makes its own copy of the values you feed into it. So your list will still be in good shape! Just be cautious with pointers, though—if you point to a temporary variable's address, that's where things can get messy and lead to undefined behavior.
Got it! So, as long as I’m inserting actual objects and not just pointers to local variables, it should all be fine.

Thanks for the reassurance! What if I inserted a reference instead of a copy? Would that change anything?