The more I read about lambdas the more I hear from people that they are just function objects/functors in disguise (unless they don't capture anything, in which case they're just free static functions. I want to write lambdas at the local scope and pass them to a universal event handler, which calls them as needed, and I'm starting to notice that I can hardly do anything that a traditional function object lets me do. Please let me know if my understanding of this is wrong, as I've commented a whole bunch of stuff you can do with functors and can't with lambdas, as far as I know:
#include <iostream>
#include <vector>
struct MyFunctorClass
{
// Custom constructor, can't do with lambda
MyFunctorClass(int& capturedVariable) : capturedVariable(capturedVariable)
{ std::cout << "I can do anything on construction.\n"; }
// Overloading constructors, different ways to initialise function object, can't do with lambda
MyFunctorClass(int& capturedVariable, int sizeOfBuffer) : capturedVariable(capturedVariable)
{ heapAllocation = new int[sizeOfBuffer]; }
// Custom destructor, can't do with lambda
~MyFunctorClass() { delete[] heapAllocation; }
void operator()() { std::cout << "Standard call\n"; }
void operator()(int arg) { std::cout << "Argument passed: " << arg << '\n'; }
// operator() overloading, different ways to call the function object, can't do with lambda
int* heapAllocation; // Have heap allocated resources, can't do with lambda
bool internalStateVariable = true; // Initialise a member variable on construction, can't do with lambda
int& capturedVariable; // I can access this variable directly with MyFunctorClass::capturedVariable = 7, can't do with lambda
};
int main()
{
int localVar = 0;
bool trueOrFalse = false;
{
MyFunctorClass* myFunctionObj = new MyFunctorClass(localVar, 100);
// Can dynamically allocate function object, can't with lambda
auto lambda = new[&]() { localVar = 1; }; // Can't do?
lambda.trueOrFalse = true; // trueOrFalse isn't member of lambda, even though it captured it, doesn't make sense
} // Lambda object is destroyed here. My function object lives until I delete it.
return 0;
}
void holdFunctionObject(MyFunctorClass* funcObj)
{
static std::vector<MyFunctorClass*> list;
list.push_back(funcObj);
// I can hold all the function objects forever, they'll never go out of scope unless I delete them, can't do with lambda
}
I feel really restricted, it seems like lambdas are just a way of declaring functions "in place". They also hold state, but only can hold state of objects that are already in scope, not create new ones. And also can't be initialised in any specific ways that functors can. Have I got this right? Because they seem VERY different from just a class with overloaded operator();