是否在Exit()上调用基本对象析构函数? [英] Are Basic Object Destructors Called On Exit()?

查看:195
本文介绍了是否在Exit()上调用基本对象析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经出现了几次,但是我试图为上述问题找到一个明确的答案,但是我一直遇到冲突的信息.我需要知道的是,当我使用exit()时是否破坏了基本类对象.我知道需要删除动态内存,但我的意思是:

I realise this question has come up a few times, but I'm trying to get a definitive answer for the above question, but I keep coming across conflicting info. What I need to know is if a basic class object is destructed when I use exit(). I'm aware of dynamic memory needing to be deleted, but I am meaning something more like:

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

class employee
{
    public:
        employee ();
        string name;
        ~employee();
};

employee::employee () 
{
    name = "bob";
}

employee::~employee()
{
    cout << "Object destroyed" << endl;
}

int main()
{
    employee emp1;
    exit(1);
    cout << "Hello" << endl;
}

现在,如果我从主面板上移除exit(1),则将按预期方式打印对象销毁"和问候".但是,将其保留在那里,都不会被打印.原因很明显是"Hello",但我的印象是emp1仍然会被销毁,但是销毁消息未显示...

Now if I remove exit(1) from the main, the "Object destroyed" and "Hello" are printed as expected. Leaving it in there though, neither are printed. The reason is obvious for "Hello", but I was under the impression that emp1 would still be destructed, but the destruct message isn't shown...

我正在查看此链接,其中提到了有关静态对象的信息被摧毁.上面的对象不是静态的吗?

I was looking at this link and it says about static objects being destroyed. Is the above object not considered static?

如果没有,是否有一种方法可以使程序终止而又不会与内存纠缠在一起?我的项目围绕用户输入展开,我尝试提供一个选项,如果用户输入单词"exit",则退出.

If not, is there a way to have a program terminate without it screwing with memory? My project revolves around user input and I was trying to give the option to exit if the user inputs the word 'exit'.

if(input_var == "exit")
    {
        cout << "You have chosen to exit the program." << endl;
        exit(1);
    }

是我意图的一个粗略例子.

Is a rough example of what my intent was.

推荐答案

根据此链接,它不会清理对象. 请注意,如果您使用非堆栈内存,它将调用析构函数:

According to this link, it does not clean up the object. Note that if you use non-stack memory, it will call the destructor:

static employee emp1;

第二注.任何时候使用cout调试边缘情况,对关键调试进行计时等时,都应在cout之后立即添加cout.flush(),以确保输出在继续输出之前被打印出来.我已经看到许多人使用cout来调试崩溃,并且输出从不打印,因为该程序在OS有机会打印输出之前就终止了.

Second note. Any time you are using cout for debugging edge cases, timing critical debugging, etc., you should add a cout.flush() right after the coutto ensure your output is printed before it moves on. I have seen many people use cout for debugging crashes and the output never prints because the program terminates before the OS had a chance to print the output.

这篇关于是否在Exit()上调用基本对象析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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