我有这样的东西:
#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/