lambda 与函数对象

lambda vs function object

由于缺少复制构造函数,以下代码片段无法编译。

template <typename Func>
void print(Func f) {
    f();
}

struct abc {
    abc() = default;
    abc(const abc&) = delete;
    abc& operator=(const abc&) = delete;

    void operator()() {
        std::cout << "f" << std::endl;
    }
};

int main() {
    abc s;

    print(s);
    
    return 0;
}

为什么会出现以下编译?我以为lambda也没有copy ctor

template <typename Func>
void print(Func f) {
    f();
}

int main() {
    auto f = []() {
        std::cout << "f" << std::endl;
    };

    print(f);
    
    return 0;
}

我正在使用 g++ -std=c++11。

Why does the following compile?

因为 lambda 是可复制构造的。

I thought lambda doesn't have copy ctor either.

你想错了。 Lambda 闭包是可复制构造的,只要它们没有不可复制的值捕获。