Re: lambda capture using references in scope
On Wed, 25 Jul 2012 10:03:26 -0700 (PDT), "gast128@hotmail.com"
<gast128@hotmail.com> wrote:
Hello all,
i was surprised the other day that when u pass references in
lambda's they actually get copied when capturing by value. If u pass
a pointer, the pointer gets copied, but not the pointee. However if
u pass a reference also the thing the reference points to get
copied. Its the reverse what I would expect (atm) but oth the c++
committee often does that :(. But maybe someone has a powerful
explanation?
Example:
void Foo()
{
std::string str;
std::string& rstr = str;
std::vector<int> vec(1);
printf("%08x", &rstr);
//a copy of rstr will be made???
std::for_each(vec.cbegin(), vec.cend(), [=] (int n)
{
//rstr gets copied
printf("%08x", &rstr);
});
std::for_each(vec.cbegin(), vec.cend(), [&] (int n)
{
printf("%08x", &rstr);
});
}
Using vs2010.
Here is a code snippet from Sams Learn C++ in One Hour a Day, 7th
Edition, which covers Lambda functions (and the C++11 standard
updates) and expressions, page 161, Listing 7.11:
void DisplayNums(vector<int>& DynArray)
{
for_each (DynArray.begin(), DynArray.end(), \
[] (int Element) {cout << Element << " ";} ); // Lambda
cout << endl;
}
Since vectors are a template class, you should be able to substitute
<str> or <char> for <int>
Hope this helps.
Respectfully,
MJR
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]