假设我们有
map<int, int> count;
count[x]++;
或 count[x] += value;
操作的安全性(平台相关,编译器问题),其中 x
和 value
是整数。
我想观察的行为如下:
- 如果 key 不存在,那么在执行
count[x]++;
之后,我应该有count[x]=1
即 int 应该初始化为 0。这会因平台而异吗? - 如果它存在,运算符应该按预期工作即增加值。
供引用,有一个关于类似问题的问题here但这并没有回答平台依赖/编译器依赖部分。
换句话说,count[x]++;
或 count[x] += value;
总是有效。
最佳答案
If the key does not exist, then after execution of count[x]++;, I should have count[x]=1 i.e. int should be 0 initialized. Will this vary with platform.
不,它不会改变。该值将被值初始化。所以如果类型是基本类型,比如int
,它会被初始化为0
。这是由 C++11 标准的第 23.4.4.3/1 段指定的:
T& operator[](const key_type& x);
1 Effects: If there is no key equivalent to
x
in the map, insertsvalue_type(x, T())
into the map.
T()
对应于值初始化的事实在第 8.5/17 段中指定:
The semantics of initializers are as follows. [...]
[...]
— If the initializer is
()
, the object is value-initialized.[...]
最后,根据第 8.5/8 段:
To value-initialize an object of type
T
means:— if
T
is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is user-provided or deleted, then the object is default-initialized;— if
T
is a (possibly cv-qualified) non-union class type without a user-provided or deleted default constructor, then the object is zero-initialized and, ifT
has a non-trivial default constructor, default-initialized;— if
T
is an array type, then each element is value-initialized;— otherwise, the object is zero-initialized.
下一个问题:
If it exists, the operator should work as expected i.e. increment the value.
是的(当然是模运算符重载)。
关于c++ - count[x]++ 在 map 上的安全性如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16838591/