std :: chrono :: duration默认如何构造?

for_stack

cppreference.comThe default constructor is defaulted我还检查了C++14 draft,它在默认构造函数上什么也没说,除了声明:constexpr duration() = default;

当我运行以下代码时,我感到很惊讶。

chrono::seconds s;
cout << s.count() << endl;

每次运行它时,程序都会打印一些任意数字:140737364037104140737078676496依此类推。

似乎s没有很好地初始化。然后,我检查了编译器(GCC 4.8)的实现std::chrono::duration此类具有countint类型的数据成员(即),而没有任何类内初始化程序。并且构造函数是默认构造的。因此,数据成员实际上是未初始化的。这就是程序始终打印一些任意数字的原因。

以下是我的问题:

  1. 这是正确的行为吗?还是编译器应为数据成员提供类内初始化程序?
  2. 如果这是正确的行为,那么为什么标准不指定默认值0forstd::chrono::duration呢?
胜过

由于优化,默认构造的持续时间未初始化为零。

引用Vicente J. Botet Escriba的ISO C ++讨论中的同一问题

嗨,我猜想是要遵循这种模式,不要为您不使用的东西付费,但是霍华德会更好地解释它。

如果您希望将表示形式默认初始化为零,则只需提供一个即可

std::chrono::duration<MyInt> d; // MyInt default constructor initialize the value to zero.

首席设计师兼<chrono>时间工具作者Howard Hinnant对此进行了确认和进一步解释。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++,如何缩放std :: chrono :: duration?

如何概括 std::chrono::duration(s)?

子类化std :: chrono :: duration

std :: hash表示std :: chrono :: duration

是std :: chrono :: duration默认初始化为0

std :: chrono :: duration :: duration()如何才能成为constexpr?

使用std :: chrono :: duration跟踪超时

为什么std :: chrono :: duration基于秒

std :: chrono :: duration类型的易失对象

无限std :: chrono :: duration对象合法吗?

std :: chrono :: duration :: zero()的用途是什么

C ++ 20 std :: chrono :: duration格式的缺点

std :: chrono :: duration作为方法参数传递

如何在C ++中声明std :: chrono :: duration <double>变量

如何将std :: chrono :: duration转换为double(秒)?

如何使用std :: chrono :: duration作为模板参数?

是否在std :: chrono :: duration中定义了std :: ratio计算顺序?

将std :: string转换为std :: chrono :: duration

如何使用std :: chrono ::毫秒作为默认参数

未为`chrono :: DateTime <chrono :: Utc>`实现特征`std :: ops :: Add <std :: time :: Duration>`。

为什么不能默认构造std :: chrono time_point成员变量的std :: atomic?

如何在不使用命名空间 chrono 的情况下初始化 std::chrono::duration 常量?

无法将 std::chrono::duration 与零进行比较

std :: chrono :: duration和clang自定义类型的operator /

将std :: chrono :: duration作为成员存储的类?

将秒转换为std :: chrono :: duration吗?

比率数学不适用于std :: chrono :: duration

std :: chrono :: duration中的剩余时间测量溢出

std::chrono::duration 与不同代表之间转换的意外错误