lundi 25 septembre 2017

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?

Aucun commentaire:

Enregistrer un commentaire