gpt4 book ai didi

c++ - 对静态局部变量的 undefined reference

转载 作者:可可西里 更新时间:2023-11-01 16:37:49 27 4
gpt4 key购买 nike

这是我能想出的最简单的重现问题的例子。

template<class T>
struct X
{
static void foo()
{
static int z = 0;
[]{ z = 1; }();
}
};

int main()
{
X<int>::foo();
return 0;
}

我已经在 MinGW 4.6 和 4.7 以及 Ubuntu 中的 g++ 4.6 上试过了,所有这些都给我链接错误“对‘z’的 undefined reference ”。所以现在这让我想知道这是否合法。 VC10没问题。

如果 X 是普通类而不是模板,它会起作用。另外,我认为这与 lambda 无关,因为即使我用本地类替换 lambda 也会出现错误。

最佳答案

g++ 接受以下内容,但 VC++ 不接受:

[&z]{ z = 1; }();

此处 z 被捕获,因此 g++ 不会提示 undefined reference。然而:

5.1.2/10:

The identifiers in a capture-list are looked up using the usual rules for unqualified name lookup (3.4.1); each such lookup shall find a variable with automatic storage duration declared in the reaching scope of the local lambda expression.

z 不是自动存储。 z 因此无法被捕获。因此,g++ 的行为是不正确的,而 VC++ 是正确的。

在您的代码中,VC++ 接受而 g++ 不接受:

[]{ z = 1; }();

z 由 VC++ 作为静态存储访问,这在 lambda 主体中是允许的。 g++ 显然没有将名称 z 解析为上面声明的静态变量,因此抛出 undefined reference,而它不应该。

长话短说这可能是 g++ 中的一个错误

编辑: It is indeed a bug并在 4.7 中修复。

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

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