0

For checking the order of destruction of user defined object in stl container, I have tested following code

class A
{
public: 

    static int i;
    const int j;
    A():j(++i)
    {
        cout<<"A::A() "<< j <<endl;
    }

    ~A()
    {
        cout<<"A::~A(): "<< j <<endl;
    }
    A(const A & obj):j(++i)
    {
        cout<<"copyconstro " << j <<endl;
    }
};

int A::i = 0;
int main()
{
    vector<A> obj;
    A ab; //1
    A ad;// 2
    A c;//3
    obj.push_back(ab); //4

    vector<A> obj2;
    obj2.push_back(c); //5
}

output:

A::A() 1
A::A() 2
A::A() 3
copyconstro 4
copyconstro 5
A::~A(): 5
A::~A(): 3
A::~A(): 2
A::~A(): 1
A::~A(): 4

I am little confused after looking at output.

Does ISO C++ standard mandate any sort of destruction order of objects inside STL containers?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
peterDriscoll
  • 377
  • 4
  • 8

2 Answers2

2

The order of destruction is the reverse order in which they are constructed. In your function, the order of destruction is:

obj2
c
ad
ab
obj

When obj2 gets destructed, it destructs 5.

When c gets destructed, it destructs 3.

When ad gets destructed, it destructs 2.

When ab gets destructed, it destructs 1.

When obj gets destructed, it destructs 4.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • The question is about the order of object destruction inside STL containers, which is as TonyD pointed out [unspecified](http://stackoverflow.com/a/2083629/2507444). – Peter Clark Mar 27 '14 at 09:27
2

Your code doesn't illustrate anything about "destruction order of objects inside STL containers" - each container only has one element. You're observing order of (creation and) destruction of function-local variables: notice destruction is the reverse of construction order, and specifically that construction of 4 happens when obj is defined, not when a copy of ab is push_back-ed into it, hence "4" being destroyed last.

Anyway, to actually answer your question - no - the Standard doesn't specify element destruction order.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252