c++ - 没有映射值分配给键时调用 operator [] 的行为

标签 c++ pointers map operators g++

我有这样的东西:

#include <iostream>
#include <map>

int main() {

    std::map<int, int*> mapaString;
    int* teste = mapaString[0];
    std::cout << teste << std::endl;
    if(!teste)
        mapaString[0] = new int(0);

    std::cout << mapaString[0] << std::endl;
    std::cout << mapaString[1] << std::endl;

    return 0;
}

gcc 的文档中和 cpluplus.com只是说将调用元素的默认构造函数,但是当声明一个指针而不初始化它时,它的值将是未定义的。

当键没有分配映射值且返回类型是指针时,调用下标运算符([])时是否保证返回值为NULL指针?

最佳答案

原始类型(包括指针)的“默认构造函数”产生以 0 填充的内存,很像全局变量。

这里是相关的标准语言(来自dcl.init):

To default-initialize an object of type T means:

--if T is a non-POD class type (class), the default constructor for T is called (and the initialization is ill-formed if T has no acces- sible default constructor);

--if T is an array type, each element is default-initialized;

--otherwise, the storage for the object is zero-initialized.

...

7 An object whose initializer is an empty set of parentheses, i.e., (),
shall be default-initialized.

此外,来自 lib.map.access:

23.3.1.2 map element access [lib.map.access]

reference operator[](const key_type& x);

Returns: (*((insert(make_pair(x, T()))).first)).second.

关于c++ - 没有映射值分配给键时调用 operator [] 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4950125/

相关文章:

C++ 指针和数组...何时使用 []、* 和 &

scala - 在 scala.immutable.Map 中更新多个值的惯用方法

c++ - 如何在 C++ 中的映射中使用类型数组

C++ - 按位不是 uchar 产生 int

c - 该程序缺少/需要修复什么?

c++ - 调用不通过空指针访问成员的非静态方法是否合法/定义明确的 C++?

map - PIG UDF 加载 .gz 文件失败

scala - 在 Scala 中定义从字符串到函数的映射

c++ - 部分模板特化 SFINAE

c++ - "delete p; p = NULL(nullptr);"是反模式吗?