【发布时间】:2013-03-02 18:51:27
【问题描述】:
我的代码如下所示
template <typename KeyType, typename ValueType>
KeyType IDSystem<KeyType,ValueType>::registerParameter(const ValueType& value)
{
KeyType key = __IDCounter++;
_Map[key] = value; //crashes here
return key;
}
_Map 在哪里
std::map<KeyType, ValueType> _Map;
程序曾经在指示的地方崩溃,然后我用
替换了该行_Map.at(key) = value; //out_of_range thrown here
现在程序在同一行抛出一个 std::out_of_range 异常...
KeyType 是标准库中的 int64_t,ValueType 是指向某个类(如 MyClass*)的指针。
令人惊讶的部分是我之前使用 std::map 就像那样......并且没有出现任何问题。
我是否错误地使用了 std::map?请指教。
【问题讨论】:
-
out_of_range如果地图中尚不存在密钥:cplusplus.com/reference/map/map/at -
就目前而言,您的代码具有未定义的行为,因为
__IDCounter和_Map都保留用于实现。 -
@SamerAfach:我的意思是你不能使用这些名字。
-
@Samer 阅读此链接:stackoverflow.com/a/228797/507606
-
@SamerAfach:“规则(在 C++11 中没有改变):”。这也会影响 C++03。