首页 > 解决方案 > 这是返回指向映射中值的指针的有效方法吗?

问题描述

我遇到过这段代码,我不确定它是否安全。

template<typename K, typename V, typename C>
const V* Find(const std::map<K, V, C>& map, const K& path)
{
    auto iter = map.find(path);
    if (iter != map.end())
    {
        return &iter->second;
    }

    return nullptr;
}

它被用于这个对象:

    std::map<std::pair<std::wstring, bool>, std::pair<std::vector<std::wstring>, std::map<std::wstring, bool, CaseInsensitiveStringLessThan>>, CaseInsensitiveTargetCacheLessThan> m_paths;

比较器如下:

    struct CaseInsensitiveStringLessThan : public std::binary_function<std::wstring, std::wstring, bool> {
    bool operator()(const std::wstring& lhs, const std::wstring& rhs) const {
        if (lhs.length() == rhs.length())
        {
            // Paths in the same process tend to share a significant prefix in common. Starting backwards
            // has a better chance to hit a difference first
            auto result = std::lexicographical_compare(rhs.rbegin(), rhs.rend(), lhs.rbegin(), lhs.rend(),
                [](const wchar_t a, const wchar_t b) { return towlower(a) < towlower(b); });
            return result;
        }
        else
        {
            return lhs.length() < rhs.length();
        }
    }
    };

我担心 Find() 返回的指针是否有效,或者一旦 Find 方法退出它是否不再有效。特别是,我发现我从中获得的一些价值m_paths是腐败的,我正试图找出原因。当我通过以下方式将它们添加到地图时,我知道它们没有损坏:

    m_paths[std::make_pair(path, true)] = std::make_pair(insertion_order, resolved_paths);

但是当我稍后搜索它们时,insertion_order有时resolved_paths都指向无效的内存。如果 Find() 是问题,有什么方法可以解决它?我应该在地图中存储指针而不是成对吗?

标签: c++pointers

解决方案


推荐阅读