我的Lambda在复制构建期间未正确转换捕获的"this" [英] My lambda does not correctly convert the captured 'this' during copy construction

查看:56
本文介绍了我的Lambda在复制构建期间未正确转换捕获的"this"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将问题缩小到了这个范围

I've narrowed down my problem to exactly this

#include <iostream>
#include <functional>

struct Foo {
    std::function<Foo*()> lambda;
    Foo()
        :lambda([this](){return this;})
    {}

};

int main(){

    Foo a;
    Foo b = a; 
    std::cout << &a << " " << a.lambda() << std::endl;
    std::cout << &b << " " << b.lambda() << std::endl;
}

输出在哪里

0x7ffd9128b8a0 0x7ffd9128b8a0
0x7ffd9128b880 0x7ffd9128b8a0

我本来希望this总是指向拥有lambda的实例.但是我忘记了复制结构.在这种情况下,lambda捕获this,然后将其固定,并且无论将lambda复制多少次,它都指向this的原始值.

I originally expected that this would always point to the instance that owned the lambda. However I forgot about copy construction. In this case the lambda captures this and then it is fixed and no matter how many times the lambda is copied it points to the original value of this.

有没有办法解决此问题,以便即使在拥有对象的复制构造下,lambda始终对其拥有对象this都有引用.

Is there a way fix this so that lambda always has a reference to it's owning object this even under copy construction of the owning object.

推荐答案

听起来像您需要提供自己的特殊成员函数,不是吗?例如,对于复制构造函数:

Sounds like you need to provide your own special member functions, no? E.g., for the copy constructor:

Foo(const Foo& other)
   :lambda([this](){return this;})
{}

这篇关于我的Lambda在复制构建期间未正确转换捕获的"this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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