为什么使用 Lambdas / Closures 调用 CopyConstructor?

Why is the CopyConstructor called using Lambdas / Closures?

#include <iostream>
#include <typeinfo>

struct C {
    explicit C() {std::cout << "constructor" << std::endl; }
    C (const C&) { std::cout << "copyconstructor" << std::endl;}
    ~C() { std::cout << "destructor" << std::endl; }
};

int main(){
    C c1;
    auto f = [c1](){c1;};
    std::cout << "leaving function scope" << std::endl;
    return 0;
}

使用

编译
g++ -o a -std=c++11 test.cpp -fno-elide-constructors

生成输出:

constructor copyconstructor copyconstructor destructor leaving function scope destructor destructor

编译

g++ -o a -std=c++11 test.cpp

生成输出:

constructor copyconstructor leaving function scope destructor destructor

由于我在第二次编译时跳过了-fno-elide-constructors编译器选项,为什么生成的代码仍然调用了一次CopyConstructor?我建议 g++ 编译器会像初始化闭包一样自动使用复制省略来初始化 auto f,这会导致:

constructor construtor leaving function scope destructor destructor

I suggested that g++ compiler would automatically use copy elision for the initialization of auto f as it did for initializing the closure

但是它没有使用复制省略来初始化闭包。您看到的唯一 copyconstructor 闭包变量的初始化。这是无法消除的。即使在 C++17 中;您将始终拥有 2 个 C 对象,一个从另一个复制。

如果您希望 lambda 仅引用外部作用域,那么您应该通过引用捕获变量:[&c1]。按值捕获意味着复制它。