Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Capturing lvalue references in C++11 lambdas sample code
#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