我似乎无法理解为什么下面的类型为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) 这个问题在没有捕获的情况下访问lambda表达式中的constexpr变量回答了为什么下面示例中的ref-capture不是严格必要的.但另一方面,如果被捕获,则会收到错误.
这个错误似乎是由递归本质引发的foo().
template<typename T>
constexpr int bar(const T& x) { // NOK
//constexpr int bar(T x) { // OK
return x;
}
template<typename T>
int foo(const T& l) {
constexpr auto x = l() - 1;
auto y = [&]{return bar(x);}; // if ref-capture is used, the above bar(const T&) is NOK, why?
if constexpr(x <= 0) {
return 42;
}
else {
return foo(y);
}
}
auto l2 = []{
return 3;
};
int main() …Run Code Online (Sandbox Code Playgroud)