c++ - count[x]++ 在 map 上的安全性如何

标签 c++ stl initialization

假设我们有

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, inserts value_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, if T 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/

相关文章:

c++ - 为什么 C++ STL vector 不会超出范围

c++ - 从长 vector 中释放内存

c++ - std::string 的 strlen(str.c_str()) 和 str.length() 之间的区别

c# - C# 中简洁字段初始化的技巧

c++ - C++中的模板化比较函数

c++ - DLL 中的全局构造函数和 MSVCRT

c++ - 如何在 Windows C++ 的 cmd 中运行命令后获取退出代码

c++ - 在opencv中按权重图像划分图像的每个 channel

c# - 在结构中初始化列表

c++ - 为什么这个格式错误的程序在 g++ 中编译得很好?