总是在主线程上销毁C ++静态变量? [英] are C++ static variables always destructed on main thread?

查看:97
本文介绍了总是在主线程上销毁C ++静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短问题:

C ++ 11静态(非thread_local)静态变量是否总是在主线程上被破坏?

Are C++11 static (non thread_local) variables always destructed on main thread?

它们是否总是只在程序退出时销毁(考虑到我们不手动调用它们的析构函数)?

Are they always destroyed on program exit only (considering we do not call manually their destructors)?

更新

为简便起见,让我们假设调用了析构函数. (我们没有拔掉插头,我们没有杀死-9)

For brevity, lets assume that destructors ARE called. (we did not pull the plug, we did not kill -9)

推荐答案

全局对象的析构函数由std::exit调用. main返回时,该函数由C ++运行时调用.

Destructors of the global objects are called by std::exit. That function is called by the C++ run-time when main returns.

可以安排由输入main之外的线程调用std::exit.例如:

It is possible to arrange for std::exit to be called by a thread other than that which entered main. E.g.:

struct A
{
    A() { std::cout << std::this_thread::get_id() << '\n'; }
    ~A() { std::cout << std::this_thread::get_id() << '\n'; }
};

A a;

int main() {
    std::thread([]() { std::exit(0); }).join();
}

输出:

140599080433472
140599061243648

显示一个线程称为构造函数,另一个线程称为析构函数.

Showing that one thread called the constructor and another the destructor.

请参见 std::exit

See std::exit and std::atexit for more details.

这篇关于总是在主线程上销毁C ++静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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