c++ - 这是返回指向映射中值的指针的有效方法吗?
问题描述
我遇到过这段代码,我不确定它是否安全。
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() 是问题,有什么方法可以解决它?我应该在地图中存储指针而不是成对吗?
解决方案
推荐阅读
- json - 在每个请求问题中创建的 JSON ContractResolver
- c - 巨大的数组导致分段错误
- javascript - 在 React 中测试 API 调用 - 状态未更新
- javascript - 从 JSON 中获取最大值并显示相关数据(API/Javascript)
- apache-kafka-connect - Kafka 将 MySQL 连接到 Redshift - 日期导致错误
- javascript - 在 React 中,如何调用存在于另一个组件中的函数?
- postgresql - POSTGRES 选择为
- java - 涉及成堆卡片的问题以及应该删除顶部卡片的方法
- c# - 投射通用集合项目类型
- php - php 创建不重定向到 index.html 的帐户页面