Why destructors are not called in reverse order fo

2019-08-30 03:18发布

问题:

Destructors are called in reverse order of object creation in C++ but I do not understand why it is not maintained for array of objects.

#include <iostream>
using namespace std;
class test {
    int nmbr;
    static int c;
public:
    test(int j)
    {
        cout<<"constructor is called for object no :"<<j<<endl;
        nmbr=j;
    };
    ~test()
    {
        c++;
        cout<<"destructor is called for object no :"<<c<<endl;
    };
};

int test::c=0;

int main()
{
  test ob[]={test(1),test(2),test(3)};
  return 0;
}

The above program outputs

constructor is called for object no :1
constructor is called for object no :2
constructor is called for object no :3
destructor is called for object no :1
destructor is called for object no :2
destructor is called for object no :3

But why destructors are not called in reverse order?

回答1:

It is called in reverse order. You are printing variable c. Look at my comment in this program - "I changed here". You were printing a count variable where you should have printed the object that was being destroyed.

You can read more here: https://isocpp.org/wiki/faq/dtors#order-dtors-for-arrays

#include <iostream>
using namespace std;
class test {
    int nmbr;
    static int c;
public:
    test(int j)
    {
        cout<<"constructor is called for object no :"<<j<<endl;
        nmbr=j;
    };
    ~test()
    {
        c++;
        // I changed here
        cout<<"destructor is called for object no :"<<nmbr<<endl;
    };
};

int test::c=0;

int main()
{
  test ob[]={test(1),test(2),test(3)};
  return 0;
}


回答2:

They are, the error is with your test. In calling the destructor you are accessing a number you are setting yourself. Change the destructor output to show the actual value within the class and you will see for yourself

cout<<"destructor is called for object no :"<<nmbr<<endl;


回答3:

The destructors are called in reverse order of the constructor calls.

It is your test that is producing and printing values incorrectly.

Try this code, and you will see the expected results.

#include <iostream>

class test {
    int this_instance;
    static int number_of_instances;
public:
    test() : this_instance(number_of_instances++)
    {
        std::cout << "constructor invoked for object :"<< this_instance << '\n';
    };
    ~test()
    {
        std::cout << "destructor invoked for object :" << this_instance << '\n';
    };
};

int test::number_of_instances = 0;

int main()
{
  test first_batch[4];

  return 0;
}