【发布时间】:2018-03-11 23:33:35
【问题描述】:
我正在学习如何使用 lambda 函数。如果没有分配给变量,为什么我的最后一个 lambda 不会自动运行?之前所有的都按预期工作。
#include "stdafx.h"
#include <iostream>
#include <thread>
using namespace std;
int main()
{
std::thread t([]() {
std::cout << "thread function\n";
});
std::cout << "main thread\n";
t.join();
auto a = []() -> int {
return 1 + 2;
};
int n = a();
cout << n << endl;
auto b = []() -> void {
cout << "sup" << endl;
};
b();
//why doesn't this run automatically?
[]() -> void {
cout << "hellur!" << endl;
};
return 0;
}
【问题讨论】:
-
因为你不叫它。
-
我可以在不先将其分配给变量的情况下调用 lambda 吗?
-
是的,使用函数调用运算符
() -
...您为什么会出于好奇而这样做?为什么不简单地在其中包含实际代码而不是 lambda?