This piece of code
std::string local="abc";
return B(([&]()->void{x->SomeFunction(local);}))
captures all used variables by reference, and returns the function. Among the captured variables is the local variable local, whose lifetime ends when the scope exits, i.e. when returning from the function. So the local variable doesn't exist anymore when the lambda will be executed later, which means that the captured reference is invalid ("dangling reference").
Quoting from http://en.cppreference.com/w/cpp/language/lambda:
Dangling references
If an entity is captured by reference, implicitly or explicitly, and
the function call operator of the closure object is invoked after the
entity's lifetime has ended, undefined behavior occurs. The C++
closures do not extend the lifetimes of the captured references.
This paragraph indicates that in other languages with closure support (e.g. in JavaScript), the lifetime of variables captured by reference are extended, which is not the case in C++.
The same problem exists for the variable x which is a member variable of the class A the function was invoked on. While you probably don't have a problematic code in your test, this might become a problem, too:
B b;
// some other context
{
A a;
b = a.GetObjectB();
}
// The lambda previously returned from a.GetObjectB() is now
// stored in b. But it still refers to the now dead a.x!
b.m_function(); // BOOM!
An easy fix is to simply not capture all variables by reference but by value, so the variable gets copied into the lambda instance:
std::string local="abc";
return B(([=]()->void{x->SomeFunction(local);}))
Possible workarounds when you don't want to copy the value are discussed in my answer to a very similar question: https://stackoverflow.com/a/20928847/592323.