I would like to know the default value of variables inside a struct of static static std::unordered_map<std::string, struct>.
Here's my example code:
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
enum MyStateType
{
MY_STATE_NEW,
MY_STATE_RUN,
MY_STATE_FREE
};
struct Foo
{
int num;
MyStateType state;
};
static std::unordered_map<std::string, Foo> map;
std::cout << map["Apple"].num << '\n';
std::cout << map["Apple"].state << '\n';
}
The output result:
0
0
Program ended with exit code: 0
Is it safe to think that variables inside Foo are always initialized to 0 in the beginning?
operator[]with the STL map containers. They construct the value if it is not present. Use.at()instead.std::mapandstd::unordered_mapvia the array indexoperator[]are value-initialized. Barring user-defined construction (where you're responsible for member-initializing) a trivial type such as yours will most-definitely be zero-filled.operator[]will default-construct the element which in this case value-initializes the members to zero. “When the default allocator is used, this results in the key being copy constructed from key and the mapped value being value-initialized.”operator[]forstd::unordered_mapthe standard guarantees value initialization.operator[]usage. The standard has very specific, clear rules about what happens in that case, and further places specific conditions on the object type. Ex: it must be default-constructible, for example, either user-provided or implementation-default. When the object is constructedT()is used. Those()are important. See [dcl.init].