Why is it bad to have a local functor?

For example, what is wrong with declaring a class double inside the main function if the predicate is used only once?

#include <list> #include <algorithm> #define SIZE 10 int main() { std::list<int> myList; for(int i=0; i<SIZE ;++i) { myList.push_back(i); } class doubler { public: doubler(){} int operator()(int a) { return a + a; } } pred; std::for_each(myList.begin(), myList.end(), pred); return 0; } 
+7
source share
2 answers

The problem with this setup is that, at least in C ++ 03, you cannot use a local functor as an argument to a template, because it has no external connection. This means that from a technical point of view, the above code is not legal. However, they fix this in C ++ 0x, as these are pretty silly restrictions, and since VS2010 has rudimentary support for C ++ 0x, this code is completely fine.

In short, the answer to your question is that there is nothing wrong with it if you use compilers compatible with C ++ 0x, but otherwise you should probably refrain from this in order to maximize compatibility with multiple compilers.

+14
source
  • It is illegal until C ++ 0x
  • C ++ 0x has a better solution (lambdas / closures)

Therefore, in any case, you should use a different solution.

+5
source

All Articles