简体   繁体   中英

How does lambda capture member of a struct

My code goes like this :

struct foo {
    int first;
    int second;
};

void func(foo& A) {
    Schedule([=]() 
    {
        DoWork(A.first, A.second)
    });    
}

Does lambda capture the reference to the struct by value or does it capture the .first and and .second by value ?

Thanks,

By value, if you want to capture by ref it is [&]

If you want to capture a by value and b by ref you put [a,&b]

Take the following code:

#include <iostream>
using namespace std;

class NeedDeepCopy
{
public:
    NeedDeepCopy() 
    {
    };

    NeedDeepCopy(const NeedDeepCopy& other)
    {
        data = new int[1];
        data[0] = 0x90;
    }
    int *data;
};

void func(NeedDeepCopy& obj) {

    auto lambda = [=]() mutable 
    {
        if(*obj.data == 0x90)
            cout << "0x90 - a copy was made";
    };    

    if(*obj.data == 0x88)
        cout << "Original value is 0x88" << endl;


    lambda();
}

int main() {
    NeedDeepCopy obj;
    obj.data = new int[1];
    *obj.data = 0x88;


    func(obj);

    // your code goes here
    return 0;
}

http://ideone.com/Ws6KJX

The answer is: a copy to the entire object / structure is made . In case you're dealing with objects which need a deep copy, you need to pay attention otherwise you might get uninitialized data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM