在成员函数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