Created
August 14, 2013 22:30
-
-
Save petebarber/6236315 to your computer and use it in GitHub Desktop.
Capturing lvalue references in C++11 lambdas sample code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <typeinfo> | |
void ref2ref() | |
{ | |
std::cout << "ref2ref\n"; | |
int foo = 7; | |
int& rfoo = foo; | |
int& rfoo1 = rfoo; | |
int& rfoo2 = rfoo1; | |
std::cout << "foo:" << foo << ", rfoo:" << rfoo << ", rfoo1:" << rfoo1 << ", rfoo2:" << rfoo2 << '\n'; | |
++foo; | |
std::cout << "foo:" << foo << ", rfoo:" << rfoo << ", rfoo1:" << rfoo1 << ", rfoo2:" << rfoo2 << '\n'; | |
std::cout << "&foo:" << &foo << ", &rfoo:" << &rfoo << ", &rfoo1:" << &rfoo1 << ", &rfoo2:" << &rfoo2 << '\n'; | |
} | |
void lambda_ref2ref() | |
{ | |
std::cout << "lambda_ref2ref\n"; | |
int foo = 99; | |
int& rfoo = foo; | |
int& rfoo1 = foo; | |
std::cout << "foo:" << foo << ", rfoo:" << rfoo << ", rfoo1:" << rfoo1 << '\n'; | |
std::cout << "&foo:" << &foo << ", &rfoo:" << &rfoo << ", &rfoo1:" << &rfoo1 << '\n'; | |
auto l = [foo, rfoo, &rfoo1]() | |
{ | |
std::cout << "foo:" << foo << '\n'; | |
std::cout << "rfoo:" << rfoo << '\n'; | |
std::cout << "rfoo1:" << rfoo1 << '\n'; | |
std::cout << "&foo:" << &foo << ", &rfoo:" << &rfoo << ", &rfoo1:" << &rfoo1 << '\n'; | |
}; | |
foo = 100; | |
l(); | |
} | |
void simple_ref2nonref() | |
{ | |
int foo = 7; | |
int& rfoo = foo; | |
int bar = foo; | |
auto baz = rfoo; | |
std::cout << "typeid(baz):" << typeid(baz).name() << '\n'; | |
} | |
class Bar | |
{ | |
private: | |
int mValue; | |
public: | |
Bar(const Bar&) : mValue(9999) | |
{ | |
} | |
public: | |
Bar(const int value) : mValue(value) {} | |
int GetValue() const { return mValue; } | |
void SetValue(const int value) { mValue = value; } | |
}; | |
void prevent_capture_byvalue() | |
{ | |
// UDT with copying disallowed | |
Bar bar(1); | |
Bar& rbar = bar; | |
Bar& rbar1 = bar; | |
std::cout << "&bar:" << &bar << ", &rbar:" << &rbar<< ", &rbar1:" << &rbar1 << '\n'; | |
auto l2 = [bar, rbar, &rbar1]() | |
{ | |
std::cout << "bar:" << bar.GetValue() << '\n'; | |
std::cout << "rbar:" << rbar.GetValue() << '\n'; | |
std::cout << "rbar1:" << rbar1.GetValue() << '\n'; | |
std::cout << "&bar:" << &bar << ", &rbar:" << &rbar<< ", &rbar1:" << &rbar1 << '\n'; | |
}; | |
bar.SetValue(2); | |
l2(); | |
} | |
int main() | |
{ | |
ref2ref(); | |
lambda_ref2ref(); | |
simple_ref2nonref(); | |
prevent_capture_byvalue(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment