c++ - std::pair<> 的默认构造函数是否将基本类型(int 等)设置为零?

标签 c++

写完后:

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 is true and is_default_constructible<second_type>::value is true.
3 Effects: Value-initializes first and second.

以及§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 for T is called (and the initialization is ill-formed if T 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, if T'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 value 0 (zero), taken as an integral constant expression, converted to T;
  • 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/

相关文章:

c++ - 如何在模板类创建的指针对象上重载运算符?

c++ - 我可以检测成员函数是否存在并且可以被 C++ 中的 friend 访问吗?

c++ - Qt 多线程通信

c++ - scanf - 程序等待另一个类似的?

c++ - 如何判断棋盘上是否有棋子?

c++ - 指向存储在 map 容器中的数据的指针

java - Java、C++、Python 中的异常模型

c++ - 如何在 XAML UI 的屏幕上呈现 IWICBitmap 并在 C++ 中隐藏代码?

c++ - CMake "clang++ is not able compile a simple test program"(软呢帽 20)

c++ - 何时使用 unsigned char 指针