Search code examples
c++c++11exceptionstackheap-memory

C++ Class object in stack inserted as value of Map


I have two sample classes Sample and Hello

The Hello has a map which contains a map in heap, that map has Class Sample's object in it's value type.

class Hello
{
public:
    map<int,Sample>* samMap;
};

And my function has a code like this

Hello * h = new Hello;
{
    h->samMap = new map<int,Sample>;
    for(int i=0 ; i<100000;i++)
    {
        Sample se;
        se.a = i*2;
        se.b = i*5;
        se.vecInt = new vector<int>;
        se.vecInt->push_back(i+2);
        h->samMap->insert(make_pair(i,se));
    }
}
map<int,Sample>::iterator ss = h->samMap->find(50);
if(ss != h->samMap->end())
{
    cout << " Value : " << ss->second.a <<  " " << ss->second.b << endl;
    for(int s=0; s<ss->second.vecInt->size(); s++)
    {       
        cout << ss->second.vecInt->at(s) <<  endl;
    }
}

From the above code, the Sample object is declared and used inside a block. Once the control comes out of block the stack object have to get cleared.

But still i can iterate the map and get the Sample's objects outside the for loop without any access violation exception.How is that possible? While inserting the object to container a new copy of object is inserted ?


Solution

  • Yes. Because you're not storing a pointer or reference, a copy is made when you add it to the map.

    Of course, if class Sample has a destructor to delete vecInt, it will also need a copy constructor; otherwise the pointer in the map's copy becomes invalid when the local "original" goes out of scope.