写完后:
std::pair<int, int> x;
我能保证 x.first 和 x.second 都为零吗?或者它们有什么值(value)吗?
我关心的原因是因为我试图确定如果我访问不在 map 中的元素,是否保证值是指针的 map 返回 NULL。即,如果我这样做:
std::map<int, void*> my_map;
std::cout << int(my_map[5]) << std::endl;
那么我能保证得到零(NULL)吗?还是行为未定义?
最佳答案
是的,该保证成立。引用 C++11 标准,§20.3.2/2-3:
constexpr pair();
2 Requires:
is_default_constructible<first_type>::value
istrue
andis_default_constructible<second_type>::value
istrue
.
3 Effects: Value-initializesfirst
andsecond
.
以及§8.5/7:
To value-initialize an object of type
T
means:
- if
T
is a (possibly cv-qualified) class type with a user-provided constructor, then the default constructor forT
is called (and the initialization is ill-formed ifT
has no accessible default constructor);- if
T
is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, ifT
's implicitly-declared default constructor is non-trivial, that constructor is called.- if
T
is an array type, then each element is value-initialized;- otherwise, the object is zero-initialized.
最后,§8.5/5:
To zero-initialize an object or reference of type
T
means:
- if
T
is a scalar type, the object is set to the value0
(zero), taken as an integral constant expression, converted toT
;- if
T
is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;- if
T
is a (possibly cv-qualified) union type, the object’s first non-static named data member is zero-initialized and padding is initialized to zero bits;- if
T
is an array type, each element is zero-initialized;- if
T
is a reference type, no initialization is performed.
关于c++ - std::pair<> 的默认构造函数是否将基本类型(int 等)设置为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9025792/