C++ C+中的静态变量+;兰博达斯
以下代码可以正常工作:C++ C+中的静态变量+;兰博达斯,c++,c++11,lambda,C++,C++11,Lambda,以下代码可以正常工作: #include <iostream> #include <functional> std::function<int (void)> get_incrementer() { return []() { static int count = 0; return count++; }; } int main() { using std::cout; auto incre
#include <iostream>
#include <functional>
std::function<int (void)> get_incrementer() {
return []() {
static int count = 0;
return count++;
};
}
int main() {
using std::cout;
auto incrementer = get_incrementer();
cout << incrementer() << std::endl;
cout << incrementer() << std::endl;
return 0;
}
#包括
#包括
std::函数get_incrementer(){
返回[](){
静态整数计数=0;
返回计数++;
};
}
int main(){
使用std::cout;
auto incrementer=get_incrementer();
CUT< P> C++允许它,因为C++不是安全的语言。虽然这个案例可能是“琐碎的”来检查(并且,个人而言,我不同意它是微不足道的,但我不是编译器编写者),有很多其他的情况是不需要检查的。
C++不负责为您修复损坏的代码,它只执行您告诉它的操作,即使这是非常不明智的
此外,还不完全清楚您打算让这段代码做什么。例如,这是两件完全不同的事情:
std::function<int (void)> get_incrementer() {
return []() {
static int count = 0;
return count++;
};
}
std::function<int (void)> get_incrementer() {
int count = 0;
return [count]() mutable {
return count++;
};
}
std::函数get\u incrementer(){
返回[](){
静态整数计数=0;
返回计数++;
};
}
std::函数get_incrementer(){
整数计数=0;
返回[计数]()可变{
返回计数++;
};
}
在第一种情况下,返回函数的每个实例都将共享相同的增量计数。在第二种情况下,每次调用get\u incrementer
,都将获得一个单独的对象,该对象具有自己的增量计数
用户想要哪一个?不清楚。所以你不能随意“纠正”它。你明确告诉编译器你想引用变量,所以它假设你有你的理由,并且按照你告诉它的去做
你是大师,编译器只是为了满足你的需要,服从你的意愿。
在某些情况下,当它认为您正在做一些特别奇怪的事情时,它可能会警告您,但如果您坚持,它会尊重您的权威,并编译那些看起来很奇怪的代码
在局部变量超出作用域后使用对局部变量的引用始终是未定义的行为,也不会有任何好处,使用lambda来做这件事并不特别。检查捕获作用域内变量的lambda是否离开该作用域似乎很简单。@Overv:a“lambda”不是某种特殊的构造;它只是编写简单的函子类并为其创建实例的一种简捷方法。这意味着编译器不能将它们与用户定义的类区别对待。只是因为有些东西“看起来微不足道”不会让它变得微不足道。如果我想得到最后一个案例的行为,我是否需要生成一个函子来代替?@Overv:如果你想得到最后一个案例的行为,你就使用最后一个案例。这是功能完美的代码。我的编译器(VS2012)不允许,说count
不是可修改的l值。我对GCC也有同样的问题,说它是只读的。
std::function<int (void)> get_incrementer() {
return []() {
static int count = 0;
return count++;
};
}
std::function<int (void)> get_incrementer() {
int count = 0;
return [count]() mutable {
return count++;
};
}