gpt4 book ai didi

c++ - 奇怪的 GCC 编译错误(包括简单示例)

转载 作者:IT老高 更新时间:2023-10-28 21:56:41 33 4
gpt4 key购买 nike

这是一个非常基本的问题,但我不明白为什么下面的代码不能在 GCC 4.6.1 上编译。它确实在带有 SP1 的 VS 2008 上编译:

#include <iostream>

class MyClass
{
public:
const static int MinValue = -1000;
const static int MaxValue = 1000;
};

void printValue(int i)
{
std::cout << i << std::endl;
}

int main(int argc, char** argv)
{
printValue(MyClass::MinValue);
printValue(MyClass::MaxValue);
printValue(argc < 42 ? MyClass::MinValue : MyClass::MaxValue); //This line gives the error
}

GCC 说:

david@David-Laptop:~/temp$ g++ test.cpp
/tmp/ccN2b95G.o: In function `main':
test.cpp:(.text+0x54): undefined reference to `MyClass::MinValue'
test.cpp:(.text+0x5c): undefined reference to `MyClass::MaxValue'
collect2: ld returned 1 exit status

但是,如果我对“printValue”进行第三次调用,那么它会正确构建并运行。所以这与“?”有关。运算符(operator)……这样用是不是无效?此外,如果我将 'argc < 42' 替换为 'true' 或 'false' 它也可以正常构建。

有什么想法吗?!

最佳答案

根据“一个定义规则”,如果变量是odr-used,则变量必须只有一个定义。这是由 C++11 标准定义的:

3.2/2 A variable or non-overloaded function whose name appears as a potentially-evaluated expression is odr-used unless it is an object that satisfies the requirements for appearing in a constant expression and the lvalue-to-rvalue conversion is immediately applied.

以及 ODR 本身:

3.2/3 Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required.

作为函数调用参数,它们不是odr-used:它们是在声明中指定值的常量,因此可以出现在常量表达式中;它们是按值传递的,因此会立即转换为右值。

在条件表达式中使用它们时不是这种情况。由于两者都是指向同一类型的左值,因此根据定义条件运算符的相当复杂的规则之一,条件表达式的结果将是一个左值:

5.16/4 If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category.

(此规则允许像 (a?b:c)=d 这样的表达式。)

所以常量本身并不会立即转换为右值,并且由于运行时条件,条件表达式不能出现在常量表达式中;因此,它们是 odr-used,因此需要一个定义。

正如您所注意到的,将条件更改为常量表达式可以修复链接错误;改变一个常数的类型也是如此。但目前的表达方式要求它们在一个(并且只有一个)翻译单元中有一个定义:

const int MyClass::MinValue;
const int MyClass::MaxValue;

关于c++ - 奇怪的 GCC 编译错误(包括简单示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8879944/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com