Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My lambda does not correctly convert the captured 'this' during copy construction

Tags:

c++

lambda

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;
}

where the output is

0x7ffd9128b8a0 0x7ffd9128b8a0
0x7ffd9128b880 0x7ffd9128b8a0

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.

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.

like image 686
bradgonesurfing Avatar asked Dec 18 '22 16:12

bradgonesurfing


1 Answers

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;})
{}
like image 159
lubgr Avatar answered Dec 20 '22 05:12

lubgr