inline variable is initialized more than once

后端 未结 3 1016
再見小時候
再見小時候 2020-12-18 02:59

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

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 03:33

    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 
    
    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();
    }
    

    Output (Debug)

    Constructing a Foo
    Constructing a Foo
    00007FF74FD50170
    00007FF74FD50170
    Destructing a Foo
    Destructing a Foo
    

提交回复
热议问题