0

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?

Paul Grinberg
  • 1,184
  • 14
  • 37
  • C++'s Llibrary containers store copies. You're printing out the destruction of the copies, but not the fact that copies were made. – user4581301 Oct 23 '19 at 21:17
  • Not the most perfect duplicate, but the idea is generally the same. – Yksisarvinen Oct 23 '19 at 21:17
  • Or this one: [Why is the destructor of the class called twice?](https://stackoverflow.com/questions/2627540/why-is-the-destructor-of-the-class-called-twice) – Yksisarvinen Oct 23 '19 at 21:18
  • @Yksisarvinen Agreed waffled over the first, god hammering the second. – user4581301 Oct 23 '19 at 21:19
  • 1
    Though to be honest, you need to read both to get the full measure of what's going on. I'm still looking for a closer hit. – user4581301 Oct 23 '19 at 21:20
  • You probably should read up about *copy constructors* and *move constructors* in general, their *implicitly defined* versions, and how *pass by value* works for class types. – walnut Oct 23 '19 at 21:22

0 Answers0