I have a lambda inside of a function that is capturing with [&]
and then using a local static variable inside the lambda. I'm not sure if this valid to begin with, but this compiles and links fine:
void Foo()
{
static int i = 5;
auto bar = [&]()
{
i++;
};
bar();
}
int main()
{
Foo();
}
But by making Foo
a templated function:
template <typename T>
void Foo()
{
static int i = 5;
auto bar = [&]()
{
i++;
};
bar();
}
int main()
{
Foo<int>();
}
I get the following error:
g++-4.7 -std=c++11 main.cpp
/tmp/cctjnzIT.o: In function 'void Foo()::{lambda()#1}::operator()() const':
main.cpp:(.text+0x1a): undefined reference to 'i'
main.cpp:(.text+0x23): undefined reference to 'i'
collect2: error: ld returned 1 exit status
So, I have two questions:
- Is using
i
in the first example even valid c++? - If #1, then what is wrong with the second example? Or is this a gcc bug?