std :: chrono :: duration默认如何构造? [英] How does std::chrono::duration default constructed?
问题描述
cppreference.com 说默认的构造函数是默认的
。我还检查了 C ++ 14草案
,它在默认构造函数上什么也没说,除了声明: constexpr duration()= default;
cppreference.com says The default constructor is defaulted
. I also checked the C++14 draft
, it said nothing on the default constructor, except the declaration: constexpr duration() = default;
当我运行以下代码时,我很惊讶。
When I run the following code, I was surprised.
chrono::seconds s;
cout << s.count() << endl;
每次运行它时,程序都会打印一些任意数字: 140737364037104
, 140737078676496
等。
Each time I run it, the program prints some arbitrary numbers: 140737364037104
, 140737078676496
and so on.
似乎 s
初始化得不好。然后,我检查了编译器(GCC 4.8)的 std :: chrono :: duration
的实现。此类具有int类型的数据成员(即 count
),而没有任何类内初始化程序。并且构造函数是默认构造的。因此,数据成员实际上是未初始化的。这就是程序总是打印任意数字的原因。
It seems that s
does NOT well initialized. Then I checked my compiler (GCC 4.8)'s implementation for std::chrono::duration
. This class has a data member (i.e. the count
) of int type without any in-class initializer. And the constructor is default constructed. So the data member is, in fact, uninitialized. And that's why the program always prints some arbitrary numbers.
以下是我的问题:
- 这是正确的行为吗?还是编译器应该为数据成员提供类内初始化程序?
- 如果这是正确的行为,为什么标准不指定默认值,例如
0
,用于std :: chrono :: duration
?
- Is that the right behavior? Or the compiler should give the data member an in-class initializer?
- If that's the right behavior, why does the standard NOT specify a default value, say
0
, forstd::chrono::duration
?
推荐答案
由于优化,默认构造的持续时间未初始化为零。
引用 Vicente J. Botet Escriba 来自 ISO C ++讨论:
您好,我想是要遵循这种模式,不要为您所付出的付出可以,
,但霍华德会更好地解释。
Hi, I guess is to follow the pattern don't pay for what you don't use, but Howard would explain it better.
如果您希望将表示形式默认初始化为零,则
只能提供一个
If you want the representation to be default initialized to zero, you can just provide one that do that
std :: chrono :: duration< MyInt> d; // MyInt默认构造函数将值初始化为零。
由主设计师确认并进一步解释和< chrono>
时间实用程序( Howard Hinnant )的作者
It is confirmed and further explained by lead designer and author of <chrono>
time utilities (Howard Hinnant)
这篇关于std :: chrono :: duration默认如何构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!