【问题标题】:msvc inline static member variable redefinitionmsvc内联静态成员变量重定义
【发布时间】:2019-01-19 14:46:52
【问题描述】:

我是 C++17 的新手。考虑以下代码:

// ---------------
// in MyClass.hpp
// ---------------
#pragma once

class MyClass {
public:
    static const int A;
};

inline const int MyClass::A = 100;

// ---------------
// in test.cpp
// ---------------
#include <stdio.h>
#include "MyClass.hpp"

void test() {
    printf("test: %p\n", &MyClass::A);
}

// ---------------
// in main.cpp
// ---------------
#include <stdio.h>
#include "MyClass.hpp"

extern void test();

int main() {
    printf("main: %p\n", &MyClass::A);
    test();
}

使用 MinGW-W64 g++ 8.1.0 编译时

g++ -std=c++17 main.cpp test.cpp -o test.exe

输出是

main: 00000000004044B0
test: 00000000004044B0

按预期工作。

但是,在 MSVC 2017 中

cl /std:c++17 main.cpp test.cpp

我收到一个编译器错误,说重新定义了“public: static int const MyClass::A”。 (抱歉,编译输出中包含汉字,这里不宜直接发帖。)

为什么代码在 g++ 下工作,但在 MSVC 下失败?我是不是做错了什么?

【问题讨论】:

    标签: c++ visual-studio-2017 c++17


    【解决方案1】:

    我可以确认 Clang 在没有任何警告的情况下接受您的代码。

    让我担心的是 cppreference 显示以下注释:

    内联说明符不能将已在翻译单元中定义为非内联的函数或变量(C++17 起)重新声明。

    我无法真正确定 C++ 标准中该注释的真正原因。但是由于 cppreference 在其警告中通常是正确的,我认为这就是 MSVC 阻塞您的代码的原因。它可能会期望:

    // ---------------
    // in MyClass.hpp
    // ---------------
    #pragma once
    
    class MyClass {
    public:
        static const int A = 100;
    };
    

    为了避免之前的非内联声明后跟内联定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多