Why is the copy constructor not being created, as I expect here using a map?

I'm having problems using my custom class with std :: map. The class dynamically allocates memory for members, and I don’t want to use a pointer on the map, because I want the class to take care of deleting all the allocated memory. But the problem I am facing is that after I add an element to display when this block of code goes out of scope, the destructor object is called, although it is still on the map. I made fake code below which shows what I mean. Result: so the problem is why is the last destructor called? Thanks in advance and sorry for the long question.

Constructor Called Num:0034B7E8
Default Constructor Called Num:00000000
Copy Constructor Called Num:CCCCCCCC
Copy Constructor Called Num:CDCDCDCD
destructor called Num:CCCCCCCC
destructor called Num:00000000
destructor called Num:0034B7E8
Inserted Num:0034B7E8



class myClass
{
public:
  myClass(int num) 
  {
     mnNum = new int();
     cout << "Constructor Called Num:" << mnNum << endl;
   }

   myClass() : mnNum(NULL)
   {
      cout << "Default Constructor Called Num:" << mnNum << endl;
   }

   myClass(const myClass &copy) 
   {
      mnNum = new int(copy.mnNum);
      cout << "Copy Constructor Called Num:" << mnNum << endl;
   }

   ~myClass()
   {
      delete mnNum;
      mnNum = NULL;
   }

   int* mnNum;

 };

 map<string,myClass> mvMyMap;

 void testFunction()
 {
     myClass lcObj(1);

     mvMyMap["Test"] = lcObj;
 }


 int _tmain(int argc, _TCHAR* argv[])
 {
     testFunction();
     cout << "Inserted Num:" << mvMyMap["Test"].mnNum << endl;
 return 0;
  }
+3
2

myClass . , , , , .

+10

num mnNum. :

myClass(int num) 
{
    mnNum = new int(num);
    cout << "Constructor Called Num:" << mnNum << endl;
}

:

myClass(const myClass &copy) 
{
    mnNum = new int(*copy.mnNum);
    cout << "Copy Constructor Called Num:" << mnNum << endl;
}

, . .

-1

Source: https://habr.com/ru/post/1735137/


All Articles