问题
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;
Each time I run it, the program prints some arbitrary numbers: 140737364037104
, 140737078676496
and so on.
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.
The followings are my questions:
- 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
?
回答1:
Default constructed durations are not zero initialized due to optimization.
Quoting Vicente J. Botet Escriba from same question in ISO C++ Discussion:
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)
来源:https://stackoverflow.com/questions/46402944/how-does-stdchronoduration-default-constructed