I have distilled my question down to a very simple demo program
#include <iostream>
#include <unordered_map>
typedef struct my_struct
{
my_struct(const int &x) : x(x) { printf("constructor my_struct(%d)\n", x); };
~my_struct() { printf("destructor my_struct(%d)\n", x); };
int x;
} my_t;
static std::unordered_map<int, my_t> foo({
{1, my_struct(17)}
});
int main ()
{
printf("It is %d\n", foo.at(1).x);
return 0;
}
When compiled with the most basic g++ foo.cpp
, executing the resulting binary produces the following output
constructor my_struct(17)
destructor my_struct(17)
destructor my_struct(17)
It is 17
destructor my_struct(17)
My question is why is the destructor being called so many times? For that matter, when the destructor is called multiple times, why isn't it generating an exception? Along the same lines, how can I still be accessing the value from the map when the destructor has been called?