Ravi Gupta
Ravi Gupta

Reputation: 6450

C++ Destructors: Undefined Behaviour or not?

Consider the following piece of code

#include<iostream>
#include<string>

class A
{
    private:
        char name[10];

    public:
        A() { }
        A(const char *str)
        {
            strcpy(name, str);
            std::cout<<name<<" constructed"<<endl; 
        }
        ~A()
        {
           std::cout<<name<<" destructed"<<endl;
        }
};

int main()
{
   A a("a");
   A b("b");
   return 0;
}

O/P of the following programs comes out to be:

a constructed
b constructed
b destructed
a destructed

The only explanation I have for the above code is that since b was created after a, it should be stored above a in the stack. Now when the main finishes, b was poped out first and then a, hence its destructor got called first and then of a's.

My question is: Am I correct in thinking so or the above is an undefined behavior and may varies from compiler to compiler?

Upvotes: 3

Views: 199

Answers (2)

Greg
Greg

Reputation: 1660

Here is why order of destruction matters (and should be reversed creation order)

class Foo
{
public:
  void foo() { /* ... */ }
};

class Bar
{
public:
   Bar(Foo const & foo) foo(foo) {}
   virtual ~Bar() { this->foo.foo(); }

   Foo const & foo;
};

int main()
{
  Foo foo;
  Bar bar(foo);
  // if foo gets destroyed before bar, then bar will call method foo() on invalid reference in its destructor
  // it is much more convenient to have bar destroyed before foo in such cases
}

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258548

It does not vary, objects in automatic memory (stack) are destructed in reverse order in which they are created. It's fully specified by the standard.

C++03 15.2. Constructors and destructors

  1. [...] The automatic objects are destroyed in the reverse order of the completion of their construction.

Upvotes: 10

Related Questions