简体   繁体   English

msvc内联静态成员变量重新定义

[英]msvc inline static member variable redefinition

I'm new to C++17. 我是C ++ 17的新手。 Considering the following code: 考虑以下代码:

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

When compiled with MinGW-W64 g++ 8.1.0 使用MinGW-W64 g ++ 8.1.0编译时

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

The output is 输出是

main: 00000000004044B0
test: 00000000004044B0

which works as expected. 它按预期工作。

However, in MSVC 2017 但是,在MSVC 2017中

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

I got a compiler error, saying redefinition of "public: static int const MyClass::A". 我收到一个编译器错误,说重新定义了“ public:static int const MyClass :: A”。 (Sorry, the compiler output contains Chinese characters. It's not appropriate to post here directly.) (很抱歉,编译器输出包含中文字符。不宜直接在此处发布。)

Why the code works under g++, but fails in MSVC? 为什么代码可以在g ++下运行,但在MSVC中失败? Did I do something wrong? 我做错什么了吗?

I can confirm that Clang accepts your code without any warning. 我可以确认Clang接受了您的代码而没有任何警告。

What worries me is that cppreference shows the following note: 我担心的是cppreference显示以下注释:

The inline specifier cannot re-declare a function or variable (since C++17) that was already defined in the translation unit as non-inline. 内联说明符不能重新声明在转换单元中已定义为非内联的函数或变量(自C ++ 17起)。

I could not really identify the real cause for that note in C++ standard. 我无法真正确定C ++标准中该注释的真正原因。 But as cppreference is generally correct in its warnings, I assume that it is the reason why MSVC chokes on your code. 但是由于cppreference通常在其警告中是正确的,因此我认为这是MSVC在您的代码上造成阻塞的原因。 It would probably expect: 它可能会期望:

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

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

in order to avoid a former non inline declaration followed with an inline definition. 为了避免之前的非内联声明和内联定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM