内联变量被多次初始化 [英] inline variable is initialized more than once

查看:89
本文介绍了内联变量被多次初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些 inline const 变量的示例在Visual Studio 2017中被初始化(和销毁)了3次。这是链接器的错误吗?还是应该以其他方式发生这种情况?

Im seeing some examples of inline const variable getting initialized (and destructed) 3 times with visual studio 2017. Is this is a bug with the linker ? or is this supposed to happend in some other way ?

链接器Comdat折叠设置为关。

linker Comdat folding is set to Off.

示例代码:

#pragma once

struct A {
  A() {
    static int count = 0;
    ++count;
    ASSERT(count == 1);
  }
  ~A() {
  }
};


inline const A a = A();

在我的解决方案中,我两次使用了assert断言(一个构造函数被调用了3次)。
检查调用栈显示所有调用栈都是相同的,并且所有调用都来自于a()的动态初始化器。现在,我知道一个事实,因为我只是创建该类来研究此问题,所以该类未在解决方案的其他部分使用。

In my solution, I have the assert fire twice (A constructor called 3 times). Inspecting the call stack shows all call stacks are identical and all calls come from dynamic initializer for a(). Now I know for a fact this class is not used in other parts of the solution since I just created it to investigate this issue.

Im使用VS17 15.8.9

Im using VS17 15.8.9

更新:错误报告在这里 https://developercommunity.visualstudio.com/content/problem/297876/static-inline-variable-gets-destroyed-multiple-tim.html (您可以upvote以帮助推动该错误修正)

Update: Bug report here https://developercommunity.visualstudio.com/content/problem/297876/static-inline-variable-gets-destroyed-multiple-tim.html (you may upvote to help push for the bugfix)

推荐答案

这似乎是MSVC错误。我可以使用下面的代码(以及VS2017 15.8.9)来重现它。有趣的是,我只能使用Debug版本进行复制。在发布模式下,优化程序似乎可以拯救我们。

This appears to be an MSVC bug. I'm able to reproduce it with the code below (also with VS2017 15.8.9). Interestingly, I can only reproduce with a Debug build. In Release mode, the optimizer seems to save us.

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;

other.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

这篇关于内联变量被多次初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆