[ASK] Recursive lambdas and C-arrays

Revision ru1, by LeoPro, 2023-04-03 15:26:42

Hello!

I have yet another C++ question I want to know answer to. That is:

  • This code doesn't compile with error message use of deleted function ‘main()::<lambda(auto:1)>::~<lambda>()’
int main() { // CE
    int n = 1;
    int a[n];
    auto f = [&](auto f) -> void {
        a[0] = 0;
    };
}
  • On the other side, replacing C-array with vector or specifying array length as compile-time constant or allocating it with new — every other way makes everything to work:
int main() { // OK
    int n = 1;
    vector<int> x(n);
    int y[1];
    int *z = new int[n];
    auto f = [&](auto f) -> void {
        x[0] = y[0] = z[0] = 0;
    };
}
  • The error also goes off if the lambda f doesn't accept any arguments declared as auto. It also disappears if I capture the array by link directly: auto f = [&, &a].

So, why is it the case? I managed to find out that variable sized array are GCC extension but it doesn't clarify the doubt. The problem is not in the array allocation / initialization, but in lambda's destructor, which clearly needn't to destruct the array.

As far as I know, the array is just a pointer to its beginning and capturing it by copy, or by reference makes small difference — you either create new variable that points to the beginning of the array too, or you create a reference to the "main" pointer. Doesn't seem to be a problem.

So, this is quite a peculiar problem; it arose when I tried to combine recursive lambdas and C-arrays. Probably some C++ master would share some thoughts and improve my understanding and intuition of the language.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
ru1 Russian LeoPro 2023-04-03 15:26:42 1752 Первая редакция (опубликовано)