为什么不以相反的顺序为对象数组调用析构函数?

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

在 C++ 中,析构函数的调用顺序与对象创建的顺序相反,但我不明白为什么不为对象数组维护它。

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

以上程序输出

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

但为什么不以相反的顺序调用析构函数?

倒序调用。您正在打印变量 c。看看我在这个节目里的评论——"I changed 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;
}

是的,错误出在你的测试上。在调用析构函数时,您正在访问您自己设置的数字。更改析构函数输出以显示 class 中的实际值,您将亲眼看到

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

析构函数的调用顺序与构造函数调用的顺序相反。

是您的测试错误地生成和打印了值。

试试这个代码,你会看到预期的结果。

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