Reputation: 237
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,
Upvotes: 1
Views: 2813
Reputation: 43662
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;
}
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.
Upvotes: 1
Reputation: 3594
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]
Upvotes: 1