c++ - 对 static const int 的 undefined reference

标签 c++ gcc

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

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),那么在每种情况下传递的对象的地址必须相同。 AFAIK GCC 无法安排,除非对象在一个(且只有一个)TU 中定义。

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

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

相关文章:

c++ - 可变函数包装器

c++ - 使用 Boost.Geometry 计算线和多边形之间的交点

c++ - 来自 SPOJ 的远征问题。使用堆数据结构

android - 如何在 GCC 中使用来自不同路径的 C 库

c++ - 如何使用 PatchELF 或 chrpath 替换库共享对象

可以在用户空间代码中使用 likely/unlikely 宏吗?

c++ - 如何轻松生成具有静态存储的符号列表?

c++ - 如何使用映射C++中的值获取匹配键

c++ - 为什么解引用运算符 (*) 也用于声明指针?

c - 错误 : _mm_clmulepi64_si128 was not declared in this scope