c ++ 03:std :: map中内建类型的默认构造函数 [英] c++03: default constructor for build-in types in std::map
问题描述
我一直认为下面的代码
std :: map< int,int&测试;
std :: cout<< test [0]<< std :: endl;
将打印随机值,因为它会在地图内创建单位化值。然而,事实证明,创建的int实际上总是初始化为零和标准内置类型在某些情况下也是零初始化。
问题是:当zero-initialziation是为标准类型(int / char / float / double / size_t)执行的?我很肯定,如果我在中间无处声明 int i;
,它将包含随机数据。
问题是关于C ++ 03标准。这个问题的原因是,现在我不再确定,当我有提供内置类型的初始化,如int / float / size_t或当它可以安全地省略。
标准容器( map
,矢量
,etc ...)将始终以值初始化元素。
is:
- 如果有默认构造函数,则默认初始化
- ()
语法很简单:
code>在C ++ 11中)。T t = T();
会将值初始化t
(和T t {};
code> map< K,V> :: operator [] ,对的值部分是值初始化的,对于内置类型, > 0 。
I always thought that following code
std::map<int, int> test; std::cout << test[0] << std::endl;
would print random value, because it would create unitialized value within map. However, it turns out that created int is actually always initialized to zero AND standard builtin types are also zero-initialized in certain circumstances.
The question is : when zero-initialziation is performed for standard types (int/char/float/double/size_t)? I'm pretty sure that if I declare
int i;
in the middle of nowhere, it will contain random data.P.S. The question is about C++03 standard. The reason for the question is that now I'm no longer certain when I have to provide initialization for builtin types like int/float/size_t or when it can be safely omitted.
解决方案Standard containers (
map
,vector
, etc...) will always value-initialize their elements.Roughly speaking, value-initialization is:
- default-initialization if there is a default constructor
- zero-initialization otherwise
(Some would say, the best of both worlds)
The syntax is simple:
T t = T();
will value-initializet
(andT t{};
in C++11).When you use
map<K,V>::operator[]
, the "value" part of the pair is value-initialized, which for a built-in type yields0
.这篇关于c ++ 03:std :: map中内建类型的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!