gpt4 book ai didi

c++ - 静态成员初始值设定项的 lambda 作用域

转载 作者:可可西里 更新时间:2023-11-01 16:36:14 25 4
gpt4 key购买 nike

我的问题是关于静态成员初始值设定项的 lambda 作用域。考虑以下测试:

#include <functional>
#include <iostream>

struct S {
static const std::function<void(void)> s_func;
};

const std::function<void(void)> S::s_func = []() {
std::cout << "Hello from " << __PRETTY_FUNCTION__ << std::endl;
};

int main(void) {
S::s_func();
return 0;
}

gcc 从 4.8 开始在 S 的范围内定义了 lambda,所以程序输出是这样的:

Hello from S::<lambda()>

(gcc-4.8.2 对 __FUNCTION__ 和 Co 宏有不同的定义,但是 lambda 仍然在 S 中定义)

同时 gcc-4.7 在全局范围内定义了 lambda,因此程序输出

Hello from <lambda()>

可能较新的 gcc 更符合标准。但是,我想问一下标准是否实际指定了这个方面,或者它可以依赖于实现。

更新:@user5434961 建议所有类似 __FUNCTION__ 的宏都依赖于实现,因此最好在符合标准的测试中避免使用它们。因此,如果编译器在 S 范围内定义了此类 lambda,则可以编译该示例,否则会中断编译:

#include <functional>
#include <iostream>

struct S {
static const std::function<void(void)> s_func;
private:
static const int s_field;
};

const std::function<void(void)> S::s_func = []() {
std::cout << "Hello from S::s_func. S::s_field = " << S::s_field << std::endl;
};

const int S::s_field = 1;

int main(void) {
S::s_func();
return 0;
}

最佳答案

这个问题以前有人提出过,但我找不到相关的错误报告。这是一个 broken link对于据称已提交的 MSVC 错误报告(它在 2015 年仍未修复:您可以在 rise4fun 对其进行测试)。然而,它已被固定在 GCC 的 4.7 和 4.8 之间。用于将此作为错误支持的相关标准是:

[C++11, 9.4.2/2] The initializer expression in the definition of a static data member is in the scope of its class.

[C++11, 5.1.2/2] The evaluation of a lambda-expression results in a prvalue temporary (12.2). This temporary is called the closure object. A lambda-expression shall not appear in an unevaluated operand (Clause 5).

[C++11, 5.1.2/3] The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type — called the closure type — whose properties are described below. This class type is not an aggregate (8.5.1). The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression.

以前

Why lambda in static initializer can't access private members of class in VC++2013?

C++11 lambdas can access my private members. Why?

Why is it not possible to use private method in a lambda?

关于c++ - 静态成员初始值设定项的 lambda 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33074110/

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