Weird bug with C++ lambda expressions in VS2010
- by Andrei Tita
In a couple of my projects, the following code:
class SmallClass
{
public:
int x1, y1;
void TestFunc()
{
auto BadLambda = [&]()
{
int g = x1 + 1; //ok
int h = y1 + 1; //c2296
int l = static_cast<int>(y1); //c2440
};
int y1_copy = y1; //it works if you create a local copy
auto GoodLambda = [&]()
{
int h = y1_copy + 1; //ok
int l = this->y1 + 1; //ok
};
}
};
generates
error C2296: '+' : illegal, left operand has type 'double (__cdecl *)(double)'
or alternatively
error C2440: 'static_cast' : cannot convert from 'double (__cdecl *)(double)' to 'int'
You get the picture. It also happens if catching by value.
The error seems to be tied to the member name "y1". It happened in different classes, different projects and with (seemingly) any type for y1; for example, this code:
[...]
MyClass y1;
void TestFunc()
{
auto BadLambda = [&]()->void
{
int l = static_cast<int>(y1); //c2440
};
}
generates both these errors:
error C2440: 'static_cast' : cannot convert from 'MyClass' to 'int'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
error C2440: 'static_cast' : cannot convert from 'double (__cdecl *)(double)' to 'int'
There is no context in which this conversion is possible
It didn't, however, happen in a completely new project. I thought maybe it was related to Lua (the projects where I managed to reproduce this bug both used Lua), but I did not manage to reproduce it in a new project linking Lua.
It doesn't seem to be a known bug, and I'm at a loss. Any ideas as to why this happens? (I don't need a workaround; there are a few in the code already).
Using Visual Studio 2010 Express version 10.0.40219.1 Sp1Rel.