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
Yes, a copy is made when you do ip2int.insert<..>(..).