Why destructors are not called in reverse order for array of objects?

纵饮孤独 提交于 2019-12-12 01:52:29

问题


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;
}


来源:https://stackoverflow.com/questions/31246000/why-destructors-are-not-called-in-reverse-order-for-array-of-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!