gpt4 book ai didi

c++ - 内置类型的 std::map 默认值

转载 作者:IT老高 更新时间:2023-10-28 12:50:08 31 4
gpt4 key购买 nike

最近,我对 std::map operator[] 函数感到困惑。在 MSDN 库中,它说:“如果未找到参数键值,则将其与数据类型的默认值一起插入。”我试图为这个问题寻找更准确的解释。例如这里: std::map default value在这个页面中,Michael Anderson 说“默认值是由默认构造函数(零参数构造函数)构造的”。

现在我的任务是:“内置类型的默认值是多少?”。它与编译器有关吗?或者 c++ 标准委员会是否有针对这个问题的标准?

我在 Visual Studio 2008 上对“int”类型进行了测试,发现“int”类型的值是 0。

最佳答案

这是在标准中定义的,是的。在这种情况下,map 正在执行“默认初始化”。正如您所说,对于类类型,它调用无参数构造函数。

对于内置类型,在 '98 标准中,请参阅第 8.5 节“初始化程序”:

To default-initialize an object of type T means:

  • if T is a non-POD ...
  • if T is an array type ...
  • otherwise, the storage for the object is zero-initialized

之前,

To zero-initialize storage for an object of type T means:

  • if T is a scalar type, the storage is set to the value 0 (zero) converted to T

标量类型有:

  • 算术类型(整数、浮点)
  • 枚举类型
  • 指针类型
  • 指向成员类型的指针

特别是,您看到的整数(初始化为零)的行为是由标准定义的,您可以依赖它。

关于c++ - 内置类型的 std::map 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4523959/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com