简体   繁体   English

静态const数据成员在另一个文件中定义

[英]Static const data member defined in another file

I'm working on a static analyzer for C++11. 我正在为C ++ 11开发静态分析器。 There is an interaction between static const members of a class and linkage for which I am not sure whether it is defined. 类的静态const成员和链接之间存在交互,我不确定它是否已定义。 My static analyzer should warn for it only if this construct is not defined. 我的静态分析器只有在未定义此构造时才应警告它。

The example is this one: 这个例子是这样的:

in file f1.cpp: 在文件f1.cpp中:

struct Foo {
    static const int x = 2;
};

int main(void) {
    return *&Foo::x;
}

and in file f2.cpp: 并在文件f2.cpp中:

struct Foo {
    static int x;
};

int Foo::x;

The two files compiled and linked with clang++ -std=c++11 -Weverything f1.cpp f2.cpp cause no warning and produce a binary that returns 0. The same files when compiled with g++ -std=c++11 -Wall -Wextra -pedantic f1.cpp f2.cpp cause no warning and return 2. clang++ -std=c++11 -Weverything f1.cpp f2.cpp编译和链接的两个文件clang++ -std=c++11 -Weverything f1.cpp f2.cpp不会产生任何警告并生成一个返回0的二进制文件。使用g++ -std=c++11 -Wall -Wextra -pedantic f1.cpp f2.cpp编译时的相同文件g++ -std=c++11 -Wall -Wextra -pedantic f1.cpp f2.cpp没有警告并返回2。

My intuition is that this program is ill-defined but no warning is required, as: 我的直觉是这个程序定义不明确但不需要警告,如:

  • both names Foo::x have external linkage following N3376[basic.link]p5: 两个名字Foo :: x在N3376 [basic.link] p5之后有外部链接:

    In addition, a member function, static data member,[...] has the typedef name for linkage purposes (7.1.3), has external linkage if the name of the class has external linkage. 另外,成员函数,静态数据成员,[...]具有用于链接目的的typedef名称(7.1.3),如果类的名称具有外部链接,则具有外部链接。

  • but they break the N3376[basic.link]p10 requirement: 但他们打破了N3376 [basic.link] p10的要求:

    After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical [...] A violation of this rule on type identity does not require a diagnostic. 在对类型进行所有调整之后(其中typedef(7.1.3)被其定义替换),引用给定变量或函数的所有声明指定的类型应相同[...]违反此规则的类型标识不需要诊断。

To be 100% sure about this, a definition for these "all adjustments of types" is needed, but seems nowhere to be found in the C++11 standard. 为了100%确定这一点,需要对这些“类型的所有调整”进行定义,但在C ++ 11标准中似乎无处可寻。 Is there any, and is the reasoning above correct? 有没有,上面的推理是正确的吗?

It's an ODR violation. 这是ODR违规行为。 The Foo type has different declarations in each file. Foo类型在每个文件中具有不同的声明。

One definition says x is declared with external linkage (can be anything, determined when linking) and the other that it's a compile-time constant with value 2. 一个定义说x是用外部链接声明的(可以是任何东西,在链接时确定),另一个定义是它是一个值为2的编译时常量。

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

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