在没有预先初始化的情况下使用地图订阅运算符的结果是否安全?

Is it safe to use the results of map subscription operator, without previous initialization?

我有统计字数的代码:

std::map<std::string,int> counts;
std::string word;

while(cin>>word) 
{ 
   counts[word]+=1; //????
}

安全吗? AFAIK,counts[word] for previously unseen key, will create "value-initialised" value. "value-initialised" 对于 POD 类型是 "zero-initialised"。因此,看起来是安全的。

但是,Visual Studio中有关于某些情况下值初始化实现中的错误的信息(我不了解细节)。

所以,我的问题是:如果我想将代码与 g++ 和 Visual C++ 一起使用,那么使用像我这样的代码是否安全?

根据 C++ 标准对 class 的 operator [] 的描述 std::map

Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

所以这个声明

counts[word]+=1;

因此 counts[word] 的值最初等于 0。

如果您指的是 MS VC++ 的一些错误,那么您应该参考 Microsoft 站点中的错误描述。我不知道 MS VC++ 有这样的错误。这将是一个非常严重的错误,我怀疑它是否存在。

因此可以安全地与任何编译器一起使用。此类错误不会长期存在。:)