Search code examples
c++c++17closuresobjective-c++

Lambda captures with initializers and Objective-C++


Trying the following code, written into a .mm file and compiled with g++ -std=c++17

int x;
auto a = [c = x]{};

It results in the compiler complaining

error: 'c' was not declared in this scope

Thus it looks to me that lambdas with captures initializers are not supported in Objective-C++.

Experimenting with it I also noticed that the following compiles successfully:

int x;
int c;
auto a = [c = x]{};

But with a totally different behavior than it would have in pure C++. In fact, it looks like c and x are both being captured, and that c is then assigned the value of x.

As a matter of facts, the following code exits with a code of 2, which proves what stated above.

int x = 1;
int c;
auto a = [c = x]{return c+x;};

int main() {
    return a();
}

Haven't found this documented or even discussed anywhere, surely my fault? Does anybody have any pointer to any form of (un)official documentation on the matter? Is this an issue with the specific implementation, or a language limitation?


Solution

  • Haven't found this documented or even discussed anywhere, surely my fault? Does anybody have any pointer to any form of (un)official documentation on the matter? Is this an issue with the specific implementation, or a language limitation?

    There are no any limitations in regards to lambdas in Objective-C++. Essentially Objective-C++ is a superset of C++, and compiler should be able to properly interpret (any) legal C++ code. Every code snippet you provided as well as the following code:

    int x = 1;
    auto a = [c = x]{ return c + x; };
    
    int main()
    {
        return a();
    }
    

    ...compile without issues with Apple Clang 14 on MacOS using the following set of flags:

    % clang -x objective-c++ --std=c++17 Lambda.mm
    

    The behavior you are observing is most likely a GCC bug and doesn't require any documentation, it needs to be fixed.