Is it safe to return a constant link received from a member map iterator?

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; // or something more interesting

    // ++++++++++++++++++++++++++++++++++++++++++
    // | Is it safe to return a reference here? |
    // ++++++++++++++++++++++++++++++++++++++++++
    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;
}
+4
source share
3 answers

node , , ( ) , - - , , ( -)

+3

. , , , clear insert. , std::map std::unordered_map, , .

+3

-. - , . , -, , . . :

std::string get(const Key& k) const
-1

All Articles