为什么不以相反的顺序调用对象数组的析构函数? [英] Why destructors are not called in reverse order for array of objects?

查看:124
本文介绍了为什么不以相反的顺序调用对象数组的析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

以上程序输出

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?

推荐答案

它以相反的顺序调用。您正在打印变量c。看看我在这个程序中的评论-我在这里改变了。您正在打印一个count变量,应该在其中打印出被销毁的对象。

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.

您可以在此处了解更多信息:
https://isocpp.org/wiki/faq/dtors#order-dtors-for-arrays

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

这篇关于为什么不以相反的顺序调用对象数组的析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆