[英]How does std::chrono::duration default constructed?
cppreference.com says The default constructor is defaulted
. cppreference.com说
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;
我还检查了
C++14 draft
,它对默认构造函数什么也没说,除了声明: constexpr duration() = default;
When I run the following code, I was surprised.当我运行以下代码时,我感到很惊讶。
chrono::seconds s;
cout << s.count() << endl;
Each time I run it, the program prints some arbitrary numbers: 140737364037104
, 140737078676496
and so on.每次我运行它时,程序都会打印一些任意数字:
140737364037104
、 140737078676496
等等。
It seems that s
does NOT well initialized.似乎
s
没有很好地初始化。 Then I checked my compiler (GCC 4.8)'s implementation for std::chrono::duration
.然后我检查了我的编译器(GCC 4.8)的
std::chrono::duration
。 This class has a data member (ie the count
) of int type without any in-class initializer.这个类有一个 int 类型的数据成员(即
count
),没有任何类内初始化程序。 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.
这就是程序总是打印一些任意数字的原因。
The followings are my questions:以下是我的问题:
0
, for std::chrono::duration
?std::chrono::duration
指定默认值,比如0
?Default constructed durations are not zero initialized due to optimization.由于优化,默认构造的持续时间不是零初始化。
Quoting Vicente J. Botet Escriba from same question in ISO C++ Discussion :从ISO C++ 讨论中的同一问题引用Vicente J. Botet Escriba :
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 default constructor initialize the value to zero.
It is confirmed and further explained by lead designer and author of <chrono>
time utilities ( Howard Hinnant ) <chrono>
时间实用程序的首席设计师和作者 ( Howard Hinnant ) 确认并进一步解释了这一点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.