for_stack for_stack - 5 months ago 26
C++ Question

How does std::chrono::duration default constructed? 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:
and so on.

It seems that
does NOT well initialized. Then I checked my compiler (GCC 4.8)'s implementation for
. This class has a data member (i.e. the
) 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
    , for

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download