我正在尝试使用C++ 14的通用lambda,但是在使用std :: function时遇到了麻烦.
#include <iostream>
#include <functional>
int main()
{
const int a = 2;
std::function<void(int)> f = [&](auto b) { std::cout << a << ", " << b << std::endl; };
f(3);
}
Run Code Online (Sandbox Code Playgroud)
这无法编译,并显示错误消息error: ‘a’ was not declared in this scope.
它可以工作,如果我改为(int b).
这是一个错误吗?还是我错过了什么?
我正在使用的GCC版本是4.9.2.
我似乎无法理解为什么下面的类型为const int的代码编译:
int main()
{
using T = int;
const T x = 1;
auto lam = [] (T p) { return x+p; };
}
$ clang++ -c lambda1.cpp -std=c++11
$
Run Code Online (Sandbox Code Playgroud)
而这个类型为const double的那个不是:
int main()
{
using T = double;
const T x = 1.0;
auto lam = [] (T p) { return x+p; };
}
$ clang++ -c lambda2.cpp -std=c++11
lambda1.cpp:5:32: error: variable 'x' cannot be implicitly captured in a lambda with no capture-default specified
auto lam = [] …Run Code Online (Sandbox Code Playgroud) 我很难理解这段代码(C++ 14草案标准[conv.lval]中的一个例子)是如何调用未定义的行为的g(false).为什么constexpr让程序有效?
另外,"不访问y.n" 是什么意思?在两个调用中g()我们都返回n数据成员,为什么最后一行说它不访问它?
struct S { int n; };
auto f() {
S x { 1 };
constexpr S y { 2 };
return [&](bool b) { return (b ? y : x).n; };
}
auto g = f();
int m = g(false); // undefined behavior due to access of x.n outside its
// lifetime
int n = g(true); // OK, does not access y.n
Run Code Online (Sandbox Code Playgroud)