std::make_pair
will make a replica. It’s going to by no means return a pair with reference sorts.
Your return std::make_pair(true, myMap.at(...));
will return a std::pair<bool, MyData>
(copying the results of myMap.at(...)
), which converts to a std::pair<bool, const MyData&>
, the place the returned worth’s .second
is certain to the short-term that’s instantly destroyed. This implies your operate returns a dangling reference.
Use std::pair
‘s constructor:
// One among:
return { true, myMap.at(...) };
return std::pair<bool, const MyData&>(true, myMap.at(...));
(Additionally think about using simply const MyData*
, returning nullptr
if it’s not discovered. Barring that, std::non-obligatory<std::reference_wrapper<const MyData>>
can also be a good selection to switch pair with bool)