我看到一些 inline const
变量在 visual studio 2017 中被初始化(和销毁)3 次的示例。这是链接器的错误吗?或者这应该以其他方式发生?
链接器 Comdat 折叠设置为关闭。
示例代码:
#pragma once
struct A {
A() {
static int count = 0;
++count;
ASSERT(count == 1);
}
~A() {
}
};
inline const A a = A();
在我的解决方案中,我有两次触发断言(一个构造函数被调用了 3 次)。 检查调用堆栈显示所有调用堆栈都是相同的,并且所有调用都来自 a() 的动态初始化程序。现在我知道这个类没有用在解决方案的其他部分,因为我创建它只是为了调查这个问题。
我正在使用 VS17 15.8.9
更新:错误报告在这里 https://developercommunity.visualstudio.com/content/problem/297876/static-inline-variable-gets-destroyed-multiple-tim.html (您可以投票帮助插入错误修复)
最佳答案
这似乎是一个 MSVC 错误。我可以使用下面的代码重现它(也可以使用 VS2017 15.8.9)。有趣的是,我只能使用调试版本进行重现。在 Release 模式下,优化器似乎可以拯救我们。
Common.h
#pragma once
#include <iostream>
class Foo
{
public:
Foo()
{
std::cout << "Constructing a Foo" << std::endl;
}
~Foo()
{
std::cout << "Destructing a Foo" << std::endl;
}
};
inline Foo const Bar;
其他.cpp
#include "common.h"
void DoOtherStuff()
{
std::cout << &Bar << std::endl;
}
main.cpp
#include "common.h"
void DoStuff()
{
std::cout << &Bar << std::endl;
}
extern void DoOtherStuff();
int main()
{
DoStuff();
DoOtherStuff();
}
输出(调试)
Constructing a Foo
Constructing a Foo
00007FF74FD50170
00007FF74FD50170
Destructing a Foo
Destructing a Foo
关于c++ - 内联变量被多次初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53196700/