类成员函数中的lambda按值捕获显示奇怪的行为

在成员函数isLarger中,函数参数e由lambda值捕获。我希望复制构造函数被调用一次,但是,复制构造函数被调用了5次,我不明白为什么?另一方面,当按引用捕获e时,不会调用复制构造函数,并且行为符合预期。

#include <list>
#include <algorithm>
#include <iostream>

struct item{
    item(double price_): price{price_}{}
    item(const item& i){
        this->price = i.price;
        std::cout<<"copy-constructor called\n";
    }
    double price;
};

template<typename T>
class catalog{
public:
    catalog(std::initializer_list<T> it_):it{it_}{}
    bool isLarger(const T& e) const{
        if(it.empty()) return false;
        return(std::find_if(it.cbegin(),it.cend(),[e](const T& temp){return e.price<=temp.price;})==it.cend());
        // some more logic
    }
private:
    std::list<T> it;
};

int main(){
    catalog<item> c({item(10),item(20),item(30)});
    item ref(31);
    std::cout<<"***********************\n";
    if(c.isLarger(ref))
        std::cout<<"item is larger than all elements in catalog";
    else
        std::cout<<"item is not larger than all elements in catalog";
    return 0;
}

输出如下

copy-constructor called
copy-constructor called
copy-constructor called
***********************
copy-constructor called
copy-constructor called
copy-constructor called
copy-constructor called
copy-constructor called
item is larger than all elements in catalog
zzzkkkbbb007 回答:类成员函数中的lambda按值捕获显示奇怪的行为

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3134801.html

大家都在问