c++ - 标题中的内联全局变量崩溃多次包含
问题描述
我对 c++17 中全局变量的内联行为有疑问,它们似乎不像我理解的那样工作。一个简单的程序在退出时崩溃。
制作变量 extern 而不是 inline 并将其定义在 .cpp 文件中解决了这个问题,但我想知道为什么它首先会发生。
有人可以解释为什么以下给出例外吗?
SomeSharedInclude.h
#pragma once
#include <unordered_set>
namespace Stuff
{
inline std::unordered_set<int> global_set;
}
主文件
##include "SomeSharedInclude.h"
int main() {}
其他来源.cpp
##include "SomeSharedInclude.h"
class Test {};
程序退出后会发生以下情况:
Exception thrown: read access violation. _Pnode was 0xDDDDDDDD
调用堆栈顶部:
TestGlobalInline.exe!std::list<int,std::allocator<int> >::clear() Line 1392
TestGlobalInline.exe!std::list<int,std::allocator<int> >::_Tidy() Line 1775
TestGlobalInline.exe!std::list<int,std::allocator<int> >::~list<int,std::allocator<int> >() Line 983
TestGlobalInline.exe!std::_Hash<std::_Uset_traits<int,std::_Uhash_compare<int,std::hash<int>,std::equal_to<int> >,std::allocator<int>,0> >::~_Hash<std::_Uset_traits<int,std::_Uhash_compare<int,std::hash<int>,std::equal_to<int> >,std::allocator<int>,0> >()
TestGlobalInline.exe!std::unordered_set<int,std::hash<int>,std::equal_to<int>,std::allocator<int> >::~unordered_set<int,std::hash<int>,std::equal_to<int>,std::allocator<int> >()
TestGlobalInline.exe!Stuff::`dynamic atexit destructor for 'global_set''()
ucrtbased.dll!54205f52()
这是在 Visual Studio 社区 15.9.7 上
我已经为全局变量尝试了其他类型,例如 std::{string, vector, stack},到目前为止只有 unordered_set、unordered_map 和列表崩溃。
好的,这似乎是一个 Visual Studio 错误,其中多次调用全局内联变量的析构函数,并且这些类(std::unordered_set 等)在发生这种情况时会给出异常(其他像 std::vector 我没有检查)。
解决方案
推荐阅读
- javascript - 在使用来自 firebase 的新数据刷新之前清除反应状态字段
- laravel - 无需在 Laravel 中调用视图即可存储 rest api 数据
- latex - 为 Pandoc 插入元数据块标题和 TOC 的分页符
- php - SQL查询从多个表中获取数据并显示在html表中
- node.js - 使用同一事务在 sequelize 中插入父/子记录的正确方法(获取父 ID)
- ios - MPMusicPlayerApplicationController 在播放完 30 首歌曲后停止在后台播放
- pandas - 包含大量信息的 Matplotlib/Seaborn 箱线图
- python - 如何减去两个不同长度的列表?
- for-loop - 在 Mathematica 中循环定义变量
- c# - 如何使用最新的 Azure SDK .NET API v12 在 Blob 上获取共享访问签名?