从自身内部替换std :: function(通过将移动分配给* this?) [英] Replacing std::function from within itself (by move-assignment to *this?)

查看:121
本文介绍了从自身内部替换std :: function(通过将移动分配给* this?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将自身中的一个std::function替换为另一个std::function?

Is it possible to replace one std::function from within itself with another 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();
}

可以修改以进行编译吗?
现在的错误消息是:此lambda函数未捕获到'this'-我完全理解.但是,我不知道如何捕获functhis指针.我猜想,它甚至不在lambda内是std::function了吗?该怎么办?

Can it be modified to compile?
The error message right now is: 'this' was not captured for this lambda function - which I completely understand. I don't know, however, how I could capture func's this-pointer. I guess, it is not even a std::function inside the lambda, yet?! How can this be done?

背景:我要实现的目标如下:在给定std::function的第一次调用中,我想做一些初始化工作,然后用优化的函数替换原始函数.我想为我的函数用户透明地实现这一目标.

Background: What I want to achieve is the following: In the first invocation of a given std::function, i would like do some initialization work and then replace the original function with an optimized one. I want to achieve this transparently for the user of my function.

以上示例的预期输出为:

The expected output of the example above is:

a
b
b

a
b
b

推荐答案

您不能在lambda内使用this来引用lambda. this将仅引用封闭类,在您的情况下,该类不存在,因此您无法使用this.但是,您可以做的是捕获func并重新分配它:

You cannot use this inside a lambda to refer to the lambda. this will only refer to the enclosing class, which in your case there is none so you cannot use this. What you can do however is capture func and reassign that:

std::function<void()> func = [&func]()
{
    std::cout << "a\n";
    func = []() { std::cout << "b\n"; }; // note the missing move, a lambda
                                         // is already an rvalue
};

但是请注意,如果让func超出其作用域(例如,通过按值从函数返回它)而没有先调用它(有效地重新分配存储的函数对象),那么您将得到一个悬空引用.

Note however that if you let func outlive its scope (say by returning it from a function by value) without calling it first (effectively reassigning the stored function object) then you'll get a dangling reference.

我想,它甚至不在lambda内是std::function了吗?!

实际上是.名称在其声明符之后进入作用域,因此在类型std::function<void()>=func之前.因此,在介绍lambda时,您已经可以捕获func.

It actually is. A name comes into scope right after its declarator, so right before the =, func of type std::function<void()> is introduced. So at the point where you introduce the lambda, you can already capture func.

这篇关于从自身内部替换std :: function(通过将移动分配给* this?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆