标头中的内联全局变量崩溃多次

时间:2019-02-14 07:03:08

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

我对c ++ 17中的全局变量的内联行为有疑问,据我了解,它们似乎不起作用。一个简单的程序在退出时崩溃。

使变量extern代替内联并在.cpp文件中定义它可以解决此问题,但我想知道为什么它首先发生。

有人可以解释为什么以下给出例外吗?

SomeSharedInclude.h

#pragma once
#include <unordered_set>

namespace Stuff
{
inline std::unordered_set<int> global_set;
}

main.cpp

##include "SomeSharedInclude.h"

int main() {}

OtherSource.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和list崩溃。


好吧,这似乎是Visual Studio的错误,在全局内联变量中多次调用了析构函数,并且这些类(std :: unordered_set等)在发生这种情况时会给出异常(其他类似std :: vector的事件会不是我检查过的。)

0 个答案:

没有答案