If it _mapis a type member std::unordered_map, is it safe to return a link to _map.find(k)->second from a function, or is this behavior undefined (or just bad practice))?
It seems to work as expected, but it is like returning a temporary link. I'm not sure if this is true, or there could be other unforeseen consequences.
#include <unordered_map>
class Container
{
public:
using Key = int;
const std::string& get(const Key& k) const
{
auto it = _map.find(k);
return it->second;
}
void put(const Key& k, const std::string& v) {
_map.emplace(k, v);
}
private:
std::unordered_map<Key, std::string> _map;
};
int main(int argc, const char * argv[])
{
Container c;
c.put(42, "something");
auto str = c.get(42);
std::cout << "found " << str << std::endl;
return 0;
}
source
share