2
votes

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:

  1. Is using i in the first example even valid c++?
  2. If #1, then what is wrong with the second example? Or is this a gcc bug?
2
Technically, only variables with automatic storage duration are "captured". In both examples, the reference to i is just an ordinary valid lvalue use. - aschepler

2 Answers

4
votes

1) Yes, you can even drop & from definition because static is always accessible in lambda function. 2) It is bug: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=54276

-2
votes

1) Yes, assuming you're intending to have 'i''s value persist between calls.

2) It's not a bug in the compiler. The static instance variable needs to also be defined via a template. Please refer to this post.