Here is my code:
int main() {
std::cout << "Hello, World!" << std::endl;
std::vector<int> v{4,3,2,1,3,3,3,3,4,3,2,1,3,3,3,3};
std::mutex mtx;
int i2=2;
int i3=2;
for_each(std::execution::par,v.begin(),v.end(),[i2,i3](const int& date)mutable{
_sleep(1000);
i2++;
std::cout<<&i2<<std::endl;
std::cout<<i2<<std::endl;
});
return 0;
}
and the result is:
0000001EF70FF540
0000001EF6FFF370
0000001EF6AFF240
0000001EF6EFF350
0000001EF71FF7E0
33
3
3
3
0000001EF72FFA70
3
0000001EF73FF7E0
3
0000001EF74FF6E0
3
0000001EF75FF8C0
3
0000001EF76FF9B0
3
0000001EF77FF5D0
3
0000001EF71FF7E0
3
0000001EF6AFF240
0000001EF70FF540
0000001EF6FFF370
0000001EF6EFF350
3
3
3
3
as you can see,for each loop,i2 got a new copy,and do the incremention on that copy.So we get 2++,the answer is 3.
But when I change a little part about that code:change
for_each(std::execution::par,v.begin(),v.end(),[i2,i3](const int& date)mutable{
to
for_each(std::execution::par,v.begin(),v.end(),[i2,&i3](const int& date)mutable{
since i2 always pass by value,the output should stay the same.But now the output is:
0000003ACCCFFB20
0000003ACCCFFB20
0000003ACCCFFB20
7
0000003ACCCFFB20
0000003ACCCFFB20
7
7
7
7
0000003ACCCFFB20
8
0000003ACCCFFB20
9
0000003ACCCFFB20
10
0000003ACCCFFB20
11
0000003ACCCFFB20
12
0000003ACCCFFB20
13
0000003ACCCFFB20
0000003ACCCFFB20
0000003ACCCFFB20
0000003ACCCFFB20
0000003ACCCFFB20
18
1818
18
18
I've check that address,it is indeed one copy of the original variable i2.But why only copy one time instead multi times?