破坏静态存储持续时间对象和未定义的行为

destruction of static storage duration objects & undefined behavior

C++ 标准第 3.6.1 节说

Calling the function std::exit(int) declared in <cstdlib> terminates the program without leaving the current block and hence without destroying any objects with automatic storage duration If std::exit is called to end a program during the destruction of an object with static storage duration, the program has undefined behavior.

所以,考虑下面的简单程序

#include <iostream>
#include <cstdlib>
class test
{
    public:
        test()
        {
            std::cout<<"constructor\n";
        }
        ~test()
        {
            std::cout<<"destructor\n";
        }
};
int main()
{
    test t;
    exit(0);
}

上面程序的输出显然应该是

constructor

那么,我的问题是:

  1. 自动对象t什么时候销毁?

  2. 它会被编译器安全销毁吗?

  3. 为什么是未定义的行为?

现在,考虑对上述程序稍加修改的版本。

#include <iostream>
#include <cstdlib>
class test
{
    public:
        test()
        {
            std::cout<<"constructor\n";
        }
        ~test()
        {
            std::cout<<"destructor\n";
        }
};
int main()
{
    static test t;
    exit(0);
}

现在,我得到以下输出:

constructor

destructor

那么,由于未定义的行为,是否有可能在某些 C++ 实现中仅看到构造函数调用作为输出?

如果我理解有误,请指正。

  1. when the automatic object t will be destroyed?

从来没有。您引用的引文是“... without destroying any objects with automatic storage duration ...”

  1. Will it be safely destroyed by compiler?

没有。编译器的工作是为机器生成 运行 的代码,一旦你处于 运行 时间,编译器就不再做任何事情了。

  1. Why it is undefined behavior?

在您的示例中,这不是未定义的行为 - 您没有调用 std::exit() "during the destruction of an object with static or thread storage duration." 但是,如果您调用了 "it's undefined behavior because the standard explicitly states it as such."