tags:

views:

81

answers:

3

Friends

Containers have automatic memory management mechanism . When values are inserted using copy Constructor and when values are removed , destructor is called for each value. After the no of elements are read, what stage desctuctor gets called ?

How does a container class handle memory when elements are read not erased ?

Many thanks

A: 

The objects in a container gets destructed when you explicitly erase elements and when your container goes out of scope.

Viktor Sehr
+2  A: 

How does a container class handle memory when elements are read not erased ?

It doesn't. There is no memory handling to be done.

When objects are created, memory for them must be allocated, and when they are destroyed, memory must be released.

When you read an existing element, you are not creating or destroying anything, so the container doesn't need to do anything.

jalf
Thanks So memory gets released when container goes out of scope . or you apply erase i.e then destructor gets called .
ronan
+1  A: 

Containers don't have memory management, objects have memory management.

obj a;
{
    std::vector<obj> b;
    b.push_back( a );//copy of 'a' taken here
}//copy of 'a' in vector destructed here because the copy goes out of scope not specifically the vector

//'a' still exists

alternatively

obj* a = new obj;
{
    std::vector<obj*> b;
    b.push_back( a );
    b.push_back( new obj );//pointer of type obj taken here
}//obj destructor not called
//got a memory leak as the obj created still exists but has no reference
delete a;//but can still delete a
Patrick
very well explained . Thanks
ronan