gpt4 book ai didi

c++ - C++ 静态变量总是在主线程上被破坏吗?

转载 作者:可可西里 更新时间:2023-11-01 17:34:30 27 4
gpt4 key购买 nike

小问题:

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

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

更新

为简洁起见,假设调用了析构函数。 (我们没有拔插头,我们没有杀-9)

最佳答案

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

可以安排 std::exit 被进入 main 的线程以外的线程调用。例如:

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

显示一个线程调用了构造函数,另一个线程调用了析构函数。

参见 std::exitstd::atexit了解更多详情。

关于c++ - C++ 静态变量总是在主线程上被破坏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47208062/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com