首页 > 解决方案 > 标题中的内联全局变量崩溃多次包含

问题描述

我对 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 我没有检查)。

标签: c++global-variablesc++17inline

解决方案


推荐阅读