gpt4 book ai didi

c++ - 对静态 const int 的 undefined reference

转载 作者:IT老高 更新时间:2023-10-28 12:08:39 24 4
gpt4 key购买 nike

我今天遇到了一个有趣的问题。考虑这个简单的例子:

template <typename T>
void foo(const T & a) { /* code */ }

// This would also fail
// void foo(const int & a) { /* code */ }

class Bar
{
public:
static const int kConst = 1;
void func()
{
foo(kConst); // This is the important line
}
};

int main()
{
Bar b;
b.func();
}

编译时出现错误:

Undefined reference to 'Bar::kConst'

现在,我很确定这是因为 static const int 没有在任何地方定义,这是故意的,因为根据我的理解,编译器应该能够在编译时进行替换-时间,不需要定义。但是,由于该函数采用 const int & 参数,它似乎没有进行替换,而是更喜欢引用。我可以通过进行以下更改来解决此问题:

foo(static_cast<int>(kConst));

我相信这现在迫使编译器生成一个临时 int,然后传递一个对它的引用,它可以在编译时成功地做到这一点。

我想知道这是否是故意的,还是我对 gcc 的期望太高而无法处理这种情况?或者这是出于某种原因我不应该做的事情?

最佳答案

这是故意的,9.4.2/4 说:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19) In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program

当您通过 const 引用传递静态数据成员时,您“使用”它,3.2/2:

An expression is potentially evaluated unless it appears where an integral constant expression is required (see 5.19), is the operand of the sizeof operator (5.3.3), or is the operand of the typeid operator and the expression does not designate an lvalue of polymorphic class type (5.2.8). An object or non-overloaded function is used if its name appears in a potentially-evaluated expression.

所以事实上,当你通过值或在 static_cast 中传递它时,你也“使用”了它。只是 GCC 在一种情况下让你摆脱了困境,但在另一种情况下却没有。

[编辑:gcc 正在应用 C++0x 草案中的规则:“名称显示为潜在评估表达式的变量或非重载函数是 odr-used,除非它是满足出现要求的对象在常量表达式 (5.19) 中,立即应用左值到右值的转换 (4.1)。”。静态转换立即执行左值-右值转换,因此在 C++0x 中它没有被“使用”。]

const 引用的实际问题是 foo 有权获取其参数的地址,并将其与另一个调用的参数地址进行比较,例如存储在全局的。由于静态数据成员是唯一的对象,这意味着如果您从两个不同的 TU 调用 foo(kConst),那么在每种情况下传递的对象的地址必须相同。除非对象在一个(并且只有一个)TU 中定义,否则 AFAIK GCC 无法安排。

好的,所以在这种情况下,foo 是一个模板,因此定义在所有 TU 中都是可见的,所以编译器理论上可以排除它对地址做任何事情的风险。但总的来说,您当然不应该获取不存在对象的地址或引用;-)

关于c++ - 对静态 const int 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5391973/

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