In member function isLarger
, the function parameter e
is captured by the lambda by-value. I expect the copy-constructor to be called once, however, the copy-constructor gets called 5 times which I am not able to understand why? On the other hand, when e
is captured by-reference, the copy-constructor is not called and the behavior is as expected.
#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;
}
The output is as follows
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