Advertisement
Guest User

Untitled

a guest
Aug 24th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. class My_class {
  2. int x = 0;
  3. // ...
  4.  
  5. void f() {
  6. int i = 0;
  7. // ...
  8.  
  9. auto lambda = [=]{ use(i, x); }; // BAD: "looks like" copy/value capture
  10. // [&] has identical semantics and copies the this pointer under the current rules
  11. // [=,this] and [&,this] are not much better, and confusing
  12.  
  13. x = 42;
  14. lambda(); // calls use(42);
  15. x = 43;
  16. lambda(); // calls use(43);
  17.  
  18. // ...
  19.  
  20. auto lambda2 = [i, this]{ use(i, x); }; // ok, most explicit and least confusing
  21.  
  22. // ...
  23. }
  24.  
  25. auto lambda = [=]{ use(i, x); };
  26.  
  27. auto lambda2 = [i, this]{ use(i, x); };
  28.  
  29. #include<iostream>
  30. using namespace std;
  31.  
  32. class My_class {
  33. public:
  34. int x = 0;
  35. // ...
  36.  
  37. void f() {
  38. int i = 0;
  39. // ...
  40.  
  41. auto lambda = [=]{ cout<<i<<x<<endl; }; // BAD: "looks like" copy/value capture
  42. // [&] has identical semantics and copies the this pointer under the current rules
  43. // [=,this] and [&,this] are not much better, and confusing
  44.  
  45. x = 42;
  46. lambda(); // calls use(42);
  47. x = 43;
  48. lambda(); // calls use(43);
  49.  
  50. // ...
  51.  
  52. auto lambda2 = [i, this]{ cout<<i<<x<<endl; }; // ok, most explicit and least confusing
  53.  
  54. lambda2();
  55. }
  56. };
  57.  
  58. int main()
  59. {
  60. My_class val;
  61. val.f();
  62. }
  63.  
  64. 042
  65. 043
  66. 043
  67. Program ended with exit code: 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement