Ceros Ceros - 2 months ago 14
C++ Question

Functor for find_if and map, avoid copy of value

Is there a way to avoid the copy (I guess that's what's going on under the hood) for the value in the

for the functor with a

struct request_number_find
request_number_find(const unsigned __int64 &baseline) : _baseline(baseline) {}
bool operator() (const std::pair<guid, RadioTransmitterInformation> &arg)
//-------------------------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^
return _baseline == arg.second.mPropagationServer.mRequestNumber;
unsigned __int64 _baseline;

Even with C++11 lambda

auto it = std::find_if(mRTMap.begin(), mRTMap.end(),
[](const std::pair<guid, RadioTransmitterInformation> &t) -> bool {
return t.second.mPropagationServer.mRequestNumber == 24031;

In both cases, I always see the destructor of
getting call multiple times while searching for the value.

Map declaration:

std::map<guid, RadioTransmitterInformation, guid_compare> mRTMap;


struct guid_compare {
bool operator() (const guid& lhs, const guid& rhs) const{
return lhs < rhs;

Find_if call:

std::find_if(mRTMap.begin(), mRTMap.end(), request_number_find(24031));


const std::pair<guid, RadioTransmitterInformation> &t

The value_type of a map always stores the key as const. But your pair here doesn't store the key as const. So to call your function, it has to copy the internal pair value into a temporary, which gets bound to a const& parameter. And thus, gets deleted after calling your lambda.

Instead, use:

const std::pair<const guid, RadioTransmitterInformation> &t

Or even better:

const decltype(mRTMap)::value_type &t

Or even better-er if you have C++14:

const auto &t