Reputation: 591
Start with the code:
#include <iostream>
#include <string>
#include <map>
#include <boost/asio.hpp>
typedef std::map<boost::asio::ip::address, int> Ip2Int;
Ip2Int ip2int;
void
func1()
{
boost::asio::ip::address addr4 = boost::asio::ip::address::from_string("192.168.2.1");
boost::asio::ip::address addr6 = boost::asio::ip::address::from_string("de::ad");
ip2int.insert(std::pair<boost::asio::ip::address, int>(addr4, 1));
ip2int.insert(std::pair<boost::asio::ip::address, int>(addr6, 2));
}
int
main()
{
func1();
Ip2Int::iterator iter = ip2int.begin();
do {
std::cout << iter->first << " -> " << iter->second << std::endl;
} while (++iter != ip2int.end());
return 0;
}
I am learning C++ and the above snippet of code has me confused. In func1 the allocation of addr4 and addr6 are stack allocations (right?). When func1 exists they should be gone(-ish, the memory will hold the value until something else uses it). This originally made me think that my walk of the ip2int map could print garbage. I was never able to make this happen though.
Since I still new to C++ I am not ruling out that I missing something. Does a copy happen somewhere that I am unaware of? I thought both the pair and the map insert calls are just making references. Which should mean they could refer to garbage at some point.
Ok, enough rambling. Is the above code somehow valid or am I just getting lucky and nothing else is coming along to use the memory that was storing addr4 and addr6?
thanks in advance for any and all help
Upvotes: 1
Views: 487
Reputation: 55395
Inserting into a std::map
makes a copy of the object. The original objects, addr4
and addr6
have automatic storage duration and are destroyed at the end of func1
, but their copies live happily in ip2int
(which has static storage duration) and are thus guaranteed to be valid during program execution.
Upvotes: 1
Reputation: 25505
Stl requires that object that use its container of which map is one are copy constructable. So what is going on hear is ip2int
is an automatic at global scope and exists for the life of the program. In Func1 you are creating two automatics and copying them into the map. Underlying the Map uses heap allocation to contain the values. When func1 exists the memory from the automatics is cleaned up and there destructors are called, but map still exists and the copies that were created still exist.
Upvotes: 0
Reputation: 15944
This code is valid. When you insert the address/int pair into the map, you are actually making a copy of the address object. So the stack-local address object named "addr4" no longer exists, but a copy of it (owned by the map) does. It's that copy that you are accessing once the function returns.
Upvotes: 2