for_stack for_stack - 23 days ago 9
C++ Question

How does std::chrono::duration default constructed?

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:


  1. Is that the right behavior? Or the compiler should give the data member an in-class initializer?

  2. If that's the right behavior, why does the standard NOT specify a default value, say
    0
    , for
    std::chrono::duration
    ?


Answer Source

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)