代码之家  ›  专栏  ›  技术社区  ›  Paul

MSVC:静态结构std::atomic<bool>测试::g_Test具有不同的类型

  •  0
  • Paul  · 技术社区  · 3 年前

    我在Visual Studio 17(2022)项目中收到了以下警告,我可以将其简化为以下内容:

    test1.cpp

    #include <atomic>
    #include "test.h"
    
    int main() {
        Test::g_test = true;
    }
    

    test2.cpp

    #include <atomic>
    
    struct A {
        std::atomic<bool> m_test = false;
    };
    
    #include "test.h"
    
    void a() {
        Test::g_test = true;
    }
    

    测试.h

    #pragma once
    
    struct Test {
        static inline std::atomic<bool> g_test = false;
    };
    

    结果:

    1>------ Build started: Project: ConsoleApplication1, Configuration: Release x64 ------
    1>test1.cpp
    1>test2.cpp
    1>LINK : warning C4744: 'static struct std::atomic<bool> Test::g_test' has different type in 'c:\consoleapplication1\test2.cpp' and 'c:\consoleapplication1\test1.cpp': '__declspec(align(1)) struct (1 bytes)' and 'struct (1 bytes)'
    

    我是否违反了某些C++规则?这是微软风险投资公司的错误吗?什么是最好的解决方案/解决方法?

    0 回复  |  直到 3 年前
        1
  •  2
  •   Paul    3 年前

    这是一个编译器错误。看见 https://github.com/microsoft/STL/issues/3241 https://developercommunity.visualstudio.com/t/10207002

    从STL错误报告减少 https://github.com/microsoft/STL/issues/3241 ,这似乎实际上是一个编译器问题。

    创建文件 a.cpp :

    template <class T> struct atomic { alignas(sizeof(T)) T x; };
    
    struct S0 { static inline atomic<bool> z; };
    
    int main() { (void) S0::z; }
    

    和文件 b.cpp :

    template <class T> struct atomic { alignas(sizeof(T)) T x; };
    
    struct S1 { atomic<bool> y; };
    
    struct S0 { static inline atomic<bool> z; };
    
    void f() { (void) S0::z; }
    

    然后使用cl/nologo/std:c++17/GL a.cpp b.cpp进行编译,它发出:

    a.cpp
    b.cpp
    warning C4744: 'static struct atomic<bool> S0::z' has different type in 'b.cpp' and 'a.cpp': '__declspec(align(1)) struct (1 bytes)' and 'struct (1 bytes)'
    Generating code
    Finished generating code
    

    值得注意的是,如果 S1 S0 在中重新排序 b.cpp