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

六眼飞鱼酱① 提交于 2020-05-13 07:10:16

问题


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?

回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!