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

标签 c++ static g++ c++11

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

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/

相关文章:

c# - 为什么我不能在公共(public)静态字符串上使用串联

c++ - 是否存在静态警告?

c++ - g++ 不正确的循环?

c++ - -std=c++11 标志在 gcc/g++ 4.4.6 中无法识别

c++ - 使用 g++ 使用 mosquitto 库编译 cpp 代码时出错

c++ - 静态转换在 C++ 中无法正常工作

c++ - 如何在 OpenCV 中找到最大矩形的坐标?

c++ - 为什么 linux 不能捕获 C++ 运行时错误,例如使用浅拷贝构造函数?

c++ - 如何在满足 if 语句后获取数组的最后一个值

reactjs - 如何将这个组件类变成纯函数无状态组件(Typescript + React)