views:

443

answers:

4

I have the following code

#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>


int main()
{
  typedef std::vector<int> Vector; 
  int sum=0;
  Vector v;
  for(int i=1;i<=10;++i)
     v.push_back(i);

  std::tr1::function<double()>  l=[&]()->double{

    std::for_each(v.begin(),v.end(),[&](int n){sum += n; //Error Here in MSVC++});
    return sum;
     };

  std::cout<<l();
  std::cin.get();
}

The above code produces an error on MSVC++ 10 whereas it compiles fine with g++ 4.5. The error produced is 1 IntelliSense: invalid reference to an outer-scope local variable in a lambda body c:\users\super user\documents\visual studio 2010\projects\lambda\lambda.cpp 19 46 lambda

So, is there any other way to access the outer-scope variable sum without explicitly creating a new variable inside the local lambda expression(inside std::for_each)?

On g++ 4.5 the code compiles fine. Does the standard(n3000 draft) say anything about it?(I don't have a copy of C++-0x(1x ?) standard at present)

A: 

I think you may have to explicitly declare the closure over sum, like so:

std::for_each(v.begin(),v.end(),[&sum](int n){sum += n;});

In general, you're supposed to be allowed to implicitly capture variables in the local scope, but only as long as the lambda is guaranteed to run in the same scope. Possibly because you're assigning your lambda to a function var and executing it later (instead of just running it directly), MSVC isn't smart enough to understand that that condition holds - after all, you could potentially pass l and execute it in some other scope - so it requires the explicit capture declaration.

tzaman
+1  A: 

Regardless of whether VC is wrong or right, it's bad style that you have sum declared outside your (outer) lambda. Since you return the value of sum, there's no need to be changing the value of an outer variable inside the loop. Instead, you should have:

int sum = 0;
std::for_each(v.begin(),v.end(),[&](int n){sum += n;});
return sum;

It could be that the nested lambdas are confusing VC, too. I'd say it's overkill to have nested lambdas, and makes for less readable code.

Neil Mayhew
+8  A: 

Have you actually tried compiling the code in the question? Visual C++ 2010 accepts the code, as is (with the comment removed, obviously), and successfully compiles the code without error.

The "error" you are seeing is not a compilation error, but an IntelliSense error. The IntelliSense error checking results in a lot of false positives (I've reported several bugs on Microsoft Connect over the past few months); in this case, IntelliSense is incorrectly saying this is an error when it is not.

You have two options: you can ignore the IntelliSense false positives or you can disable the IntelliSense error checking (right-click the Error List window and uncheck "Show IntelliSense Errors").

Either way, these IntelliSense errors in no way prevent compilation from succeeding.

James McNellis
I think you are right. The error is merely an Intellisense Error. However I tried it again and it does compile.
Prasoon Saurav
A: 

I think the sole problem you have is with that ant size red wave.... SINCE microsoft had released the compiler earlier and soon the standards body did change the rule for name look up ...so intellisense isnt upto date........

SO TRY HITTING WITH THIS IDEA.....BABY...

#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>


int main()
{
  typedef std::vector<int> Vector; 
  int sum=0;
  Vector v;
  for(int i=1;i<=10;++i)
     v.push_back(i);

  std::tr1::function<double()>  l=[&]()->double{
      int *y; y=&sum;
      std::for_each(v.begin(),v.end(),[&](int n){*y += n; });
    return sum;
     };

  std::cout<<l();
  std::cin.get();
}
peril brain
@peril brain: I have already got the answer and solved my problem. BTW there is no need to use a raw_pointer here. Even a reference to sum would have solved the problem. BTW you can turn off that `show intellisense errors` option. I hope you know that. However the code is technically correct so I've mentioned it here also: http://stackoverflow.com/questions/3221812/sum-of-elements-in-a-vector/3221813#3221813
Prasoon Saurav
if your code was technically correct I dont find a reason for posting such silly errors here in a forum ....i think if you are a good programmer you wont shot a bread in public ,so all the dogs will run after that,( an analogy to the members in this forum)...they try discussing things instead of helping out........
peril brain
@peril brain: This is not a discussion forum but a Q and A site. Initially I wasn't sure about the validity of the code in MSVC++ but after reading James' answer I realized that the error was merely an intellisense error and my code was perfectly valid. I am free to do whatever I want. If you don't like my question(or answer) don't post your answers/comments then. Its not at all required. `they try discussing things instead of helping out` Questions which are subjective and augmentative are closed immediately. It seems you are new to this site.
Prasoon Saurav