Behavior of calling operator [] when no mapped value is assigned to the key
I have something like this:
#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;
}
In documentation at gcc a开发者_开发知识库nd cpluplus.com it's just said that will be called the default constructor of the element, but when a pointer is declared without initializing it, its value will be undefined.
Is it guaranteed that the value returned will be a NULL pointer when calling subscript operator([]) when there is no mapped value assigned to the key and return type is a pointer?
The "default constructors" of primitive types (including pointers) produce 0-filled memory, much like global variables.
Here is the relevant standard language (from 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.
Also, from 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.
Just like any uninitialized variable, you cannot assume this will be initialized properly to value. It will depend on your build, release or debug, your compiler, your platform, etc. I would probably do this:
if(mapaString.find(key) == mapaString.end()) { mapaString[0] = 0; }
Then you can be sure the pointer for key was initialized to 0 / NULL.
精彩评论