samedi 28 mai 2016

Local variable class is inserted in map but it works

I have a question on local class inserting to a map.
For testing I created a class in a function without newing so that the scope is in local.
Then I inserted the class as a value in a map.
I thought then the class would be destroyed since the scope of the class is local.
However it is showing the inserted value( which is 40 in below code).
Is it that the OS has lazy delete on memory? My code is as follow

#include <cstdlib>
#include <unordered_map>
#include <iostream>

using namespace std;

class MyClass{
    public:
        MyClass(int id){m_id = id;};
        void PrintThis(){cout << " This is test "<< m_id << endl;};
        int m_id;
};

class Test{
    public:
        unordered_map<int, MyClass> mapTest2;
        void TestLocal(){
            MyClass mc1(10);
            MyClass mc2(20);
            MyClass mc3(30);

            mapTest2.insert(make_pair(1, mc1));
            mapTest2.insert(make_pair(2, mc2));
            mapTest2.insert(make_pair(3, mc3));

        }

        void TestLocal2(){
            MyClass mc1(40);
            MyClass mc2(50);
            MyClass mc3(60);

            mapTest2.insert(make_pair(4, mc1));
            mapTest2.insert(make_pair(5, mc2));
            mapTest2.insert(make_pair(6, mc3));
        }   
};   

int main(){
    Test* tt1 = new Test();
    tt1->TestLocal();
    tt1->TestLocal2();
    auto search2 = tt1->mapTest2.find(4);
    if(search2 != tt1->mapTest2.end()) {
        MyClass mc = search2->second;
        cout << mc.m_id << endl;
    }else{
        cout << "not Found2 " << endl;
    }

}

Aucun commentaire:

Enregistrer un commentaire