Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is lambda with initializer to itself equivalent to lambda without initializer?

Are the following two code snippets identical, regardless of the type and qualifiers of response, assuming that the copy constructor and copy assignment operator have no side-effects?

auto foo = [response]() {
    do_something(response);
};

And

auto foo = [response = response]() {
    do_something(response);
};

It would seem that they do exactly the same thing – copy the object response – but in certain cases, only the second version compiles.

Here is a sample program to demonstrate the issue:

#include <memory>
using namespace std;
void do_something() {
}
int main() {
    auto au = [](auto callback) {
        callback();
    };
    auto x = [&au](shared_ptr<int> response) {
        au([response = move(response)]() mutable {
            auto foo = [response/* = response*/]() { // uncomment and it will work
                do_something();
            };
        });
    };
    x(make_shared<int>(100));
}

It seems that response must be a std::shared_ptr for this issue to happen, but I'm not sure why. I understand that copying a shared_ptr does not copy the actual resource (i.e. the int), but I fail to see how it might cause the code to fail to compile. I have always believed that the top two code snippets do exactly the same thing.

If it's needed, I use MSVC 2015 and compiled it with Debug x86, but I think compiling it as Release or as x64 gives the same result.

like image 684
Bernard Avatar asked Oct 18 '25 16:10

Bernard


1 Answers

It seems to be an issue with the compiler. The latest VisualC++ v19.10.24903.0 will compile it. You can try it online here.

like image 169
AMA Avatar answered Oct 21 '25 06:10

AMA