带有初始化器的 lambda 是否等同于没有初始化器的 lambda?

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

假设复制构造函数和复制赋值运算符没有副作用,无论 response 的类型和限定符如何,以下两个代码片段是否相同?

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

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

看起来他们做的事情完全一样——复制对象响应——但在某些情况下,只有第二个版本可以编译。

下面是一个演示该问题的示例程序:

#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));
}

似乎 response 必须是 std::shared_ptr 才会出现此问题,但我不确定为什么。我知道复制 shared_ptr 不会复制实际资源(即 int),但我看不出它如何导致代码无法编译。我一直认为前两个代码片段做的事情完全一样。

如果需要,我使用 MSVC 2015 并使用 Debug x86 编译它,但我认为将其编译为 Release 或 x64 会得到相同的结果。

这似乎是编译器的问题。最新的 VisualC++ v19.10.24903.0 会编译它。你可以在线试一下here.