根据cppreference.com,C++ 11 lambda文字语法仅适用于直接初始化.似乎没有办法直接在new运算符中使用lambda语法.
我需要在堆中存储一个lambda函数,以便稍后可以从另一个线程调用它.制作lambda的副本很容易,但有没有一种简单的方法可以直接在堆中分配lambda(动态存储持续时间),而无需先在堆栈上分配它(自动存储持续时间)并制作副本?
这是一个简单的例子:
#include <cstdio>
#include <cassert>
struct MyObj {
int value;
int copies;
int moves;
MyObj(int v): value(v), copies(0), moves(0) {
printf("Created object with value %d.\n", value);
}
MyObj(const MyObj &other): value(other.value),
copies(other.copies+1), moves(other.moves) { }
MyObj(const MyObj &&other): value(other.value),
copies(other.copies), moves(other.moves+1) { }
};
int main (int argc, char **argv) {
MyObj o { 5 };
// Create lambda on stack (automatic storage duration)
auto f = [o] {
printf("Object value is …Run Code Online (Sandbox Code Playgroud) 是否有可能将std::function自己内部的一个替换为另一个std::function?
以下代码无法编译:
#include <iostream>
#include <functional>
int main()
{
std::function<void()> func = []()
{
std::cout << "a\n";
*this = std::move([]() { std::cout << "b\n"; });
};
func();
func();
func();
}
Run Code Online (Sandbox Code Playgroud)
可以对其进行修改以进行编译吗?
现在的错误消息是:此lambda函数未捕获“ this” -我完全理解。我不知道,但是,我怎么能抓住func的this终场。我想,这甚至不是std::function lambda里面了吗?如何才能做到这一点?
背景:我要实现的目标如下:在给定的第一次调用中std::function,我想做一些初始化工作,然后用优化的函数替换原始函数。我想为我的功能用户透明地实现这一目标。
上面的示例的预期输出为:
a
b
b